User Tools

Site Tools


programming-languages:bash:pos_param

Positional parameters

To pass input arguments to a script, the following syntax should be used:

./my-script.sh a b c

with code:

#!/bin/bash
 
echo "arguments total: $#"
echo "arguments given: $@"
 
count=1
while [[ $# -gt 0 ]]; do
    echo "args to pars: $#; arg $count == $1"
    count=$(($count + 1))
    shift
done

with output:

arguments total: 3
arguments given: a b c
args to pars: 3; arg 1 == a
args to pars: 2; arg 2 == b
args to pars: 1; arg 3 == c

where:

  • $# is expanded in the number of arguments;
  • $@ is expanded in the name of arguments;
  • $0 is always the pathname of the script;
  • $1, $2, .. are the single arguments in the order given.

In particular, every time the command shift is called, it shifts the total number of arguments of 1 so that:

  • $2 goes into $1;
  • $3 goes into $1;

while, at the same time, $# decreases in value.

Long and Short parameters

The following script shows how to handle optional parameters that could be passed in the short or long format.

#!/bin/bash
 
usage() {
cat <<- _EOF_
Usage: $PROGNAME [OPTION]
Take some arguments in input and print their values.
 
Mandatory arguments(*) to long options are mandatory for short options too.
    -a, --aa VAL     integer for A (*)
    -b, --bb         flag
    -c, --cc VAL     any value for C
_EOF_
}
 
PROGNAME="$(basename "$0")"
val_a=0
val_b="off"
val_c=0
 
while [[ -n "$1" ]]; do
    case "$1" in
        -a | --aa)
            if [[ "$2" =~ ^[^-] ]]; then
                shift; val_a="$1";
            fi
        ;;
        -b | --bb)
            val_b="on"
        ;;
        -c | --cc)
            if [[ "$2" =~ ^[^-] ]]; then
                shift; val_c="$1";
            fi
        ;;
        -h | --help)
            usage; exit
        ;;
        *)
            usage; exit 1
        ;;
    esac
    shift
done
 
if [[ $val_a -eq 0 ]]; then
    usage; exit
else
    echo "A == $val_a"
    echo "B == $val_b"
    echo "C == $val_c"
fi

In the beginning, the script initializes all the variables expected in input with default values.

Then, a while-loop is performed until the $1 parameter is empty: using the shift command, at the end of each loop, its value is set equal to the next parameter.

During the case test, the following cases are distinguished:

  • for optional parameters that require an input argument, after a check that this is not missing, the shift command is used to read the argument;
  • for optional parameters that are thought to be flags, no particular action is done;
  • in case of help, the exit command prints the usage function and terminates the script;
  • in all other cases not supported, the usage function is printed and the script is terminated with value >0, which means error 1)
1)
Use echo $? to return the exit status.
programming-languages/bash/pos_param.txt · Last modified: 2023/11/07 14:24 by tormec