Ricardo Morgado
Ricardo Morgado

Reputation: 48

Bash Shell - Reading option with multiple letters

I am working on a shell script that allows users to set options. The script is working fine if the user specifies options seperately. For instance:

./my_file.sh -r -l directory1 directory2

The command above is working perfectly, however my script doesn't work if the user specifies the following command:

EDIT: What I mean is that the -l option is not recognized if the user enters the command below

./my_file.sh -rl directory1 directory2

This is the code I am using to read the options

while getopts 'lvibrd:v' flag; do
  case "${flag}" in
    l) option_l=true
       shift ;;
    v) option_v=true 
       shift ;;
    i) option_i=true
       shift ;;
    b) option_b=true
       shift ;;
    r) option_r=true
       shift ;;
    d) option_d=true
       shift ;;
    *) echo "Invalid options ${flag}" 
       exit 1 ;;
  esac
done

Is there a way to read options with multiple letters, such as -rl, using similar code? Thank you in advance.

Upvotes: 0

Views: 2317

Answers (1)

buff
buff

Reputation: 2053

Try the following (simplified):

while getopts 'lr' flag; do
  case "$flag" in
    l) echo "option -l was set";;
    r) echo "option -r was set";;
    *) echo "Invalid options ${flag}"
       exit 1 ;;
  esac
done

shift $(($OPTIND - 1))
echo "$@"

Omitted shift makes the difference. The shifting confuses getopts builtin.

This works correctly for both single and combined options:

$ ./nic.sh -rl hello world
option -r was set
option -l was set
hello world

EDIT: I've added code to print the rest of arguments (after those processed by getopts).

Upvotes: 5

Related Questions