Bash parsing arguments in a function

A workaround to parsing bash script arguments in a function

execute the command:. / script.sh -t -r -e

script:

#!/bin/sh
# parse argument function
parse_args() {
echo "$#"   #<-- output: 0
}


# main
echo "$#"   #<-- output: 3

# parsing arguments
parse_args

      

+3


source to share


1 answer


$#

evaluates the number of parameters in the current area. Since each function has its own scale, and you don't pass any parameters to parse_args

, $#

there will always be 0 inside it.

To get the desired result, change the last line to:



parse_args "$@"

      

The special variable is"$@"

expanded to the positional parameters of the current (top level) as single words. They are subsequently passed on when called parse_args

.

+7


source







All Articles