0

How can I able to read the flags after the positional arguments.

echo $1
echo $2
while getopts "j:" opt; do
    echo $opt $OPTIND $OPTARG
done
$ bash test.sh arg1 arg2 -f flag1
// out: arg1
        arg2
        

Not able to get the flag. But if i place the flag argument before the positional then im able to get the flag and its arg

Cyrus
  • 84,225
  • 14
  • 89
  • 153
m9m9m
  • 1,655
  • 3
  • 21
  • 41

2 Answers2

0
$ cat test.sh
#!/usr/bin/env bash

echo "$1"
echo "$2"
shift 2
while getopts "f:" opt; do
    echo "$opt $OPTIND $OPTARG"
done

$ bash test.sh arg1 arg2 -f flag1
arg1
arg2
f 3 flag1
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

GNU handles this

$ set -- arg1 arg2 -f flag1
$ getopt -o f: -- "$@"
 -f 'flag1' -- 'arg1' 'arg2'

The way to iterate over the args is modelled in the getopt-example.bash

args=$(getopt -o 'f:' -n 'myprog.bash' -- "$@") || {
    echo 'Terminating...' >&2
    exit 1
}

eval set -- "$args"

while true; do
    case "$1" in
        '-f')
            flag=$2
            shift 2
            ;;
        '--')
            shift
            break
            ;;
        *)  echo "error: $1" >&2
            exit 1
            ;;
    esac
done

# remaining args are in "$@"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352