Home > OS >  How can i read flags after positional arguments in bash script
How can i read flags after positional arguments in bash script

Time:05-09

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

CodePudding user response:

$ 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

CodePudding user response:

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 "$@"
  • Related