Getopts when first option is a path in bash

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m having an issue with getopts in a bash script. Basically my script would have to be called with something like:

./myScript /path/to/a/folder -a -b

What I have at the top of my code is this:

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  ?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done

echo "$variable was chosen"

Now, this works as long as I call my script without /path/to/a/folder… How can I make it to work with it instead?

Thanks a lot

Answers

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html

# Call as ./myScript /path/to/a/folder -a -b

path_argument="$1"
shift   # Shifts away one argument by default

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  ?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done

echo "$variable was chosen, path argument was $path_argument"

http://stackoverflow.com/users/258523/etan-reisner http://stackoverflow.com/users/258523/etan-reisner

# Call as ./myScript -a -b /path/to/a/folder 

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  ?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done
shift $((OPTIND - 1))  # shifts away every option argument,
                       # leaving your path as $1, and every
                       # positional argument as $@
path_argument="$1"
echo "$variable was chosen, path argument was $path_argument"

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/26494331/getopts-when-first-option-is-a-path-in-bash

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils