Bash arguments

From wikinotes
Revision as of 03:14, 12 July 2020 by Will (talk | contribs) (→‎Parsing Arguments)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Arguments are handled the same way for functions and modules.


Argument Variables

$1   # first argument
$2   # second argument
# ... etc.

$#         # number of arguments
$@         # array of all arguments
${@[$#]}   # last argument


Parsing Arguments

parsing arguments in this way, it does not matter the order that parameters are passed in, or if they have are keyword arguments with a value.

# PARSE ALL ARGUMENTS

while [ $# -gt 0 ] ; do
    case $1 in
        -f|--file)
            filepath=$2
            shift 2        # jump forwards twice (once for '--file', once for 'filepath')
            ;;
        -d|--debug)
            debug=1
            shift
            ;;
        *)
            echo "default behaviour"
            ;;
    esac
done

Here is another variation

function parse_args() {
    args=($@)
    for ((i=0; i <= ${#args[@]}; i++))
    do
        case "${args[$i]}" in
            -h|--help)
                print_help
                exit 0
                ;;
            -L)
                LOCAL_PORTS+=( ${args[$i+1]} )
                ((i++))
                ;;
            -R)
                REMOTE_PORTS+=( ${args[$i+1]} )
                ((i++))
                ;;
            -t|--test)
                TEST=1
                ;;
            *)
                SSH_PARAMS+=" ${args[$i]}"
                ;;
        esac
    done
}

Counting Arguments

if [ $# -gt 2 ]; then
    echo "if there are more than 2 arguments"
fi
# see also
-eq   # equal
-ne   # not equal

-gt   # greater than
-ge   # greater or equal
-lt   # less than
-le   # less or equal

Iterating Arguments

for arg in "${args[@]}"; do
   echo $arg
done


for (( i=1; i<=(($#-1)); i++ )) ; do
	echo ${@[$i]};
done