Is the a workaround to parsing the bash script arguments in an function
run 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
Bash scripts take in command-line arguments as inputs both sequentially and also, parsed as options. The command-line utilities use these arguments to conditionally trigger functions in a Bash script or selectively choose between environments to execute the script.
Syntax for defining functions: To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.
Parsing Short Command-Line Options With getopts. In Bash, we can use both short and long command-line options. The short option starts with the single hyphen (-) character followed by a single alphanumeric character, whereas the long option starts with the double hyphen (–) characters followed by multiple characters.
$#
evaluates to the number of parameters in the current scope. Since each function has its own scope and you don't pass any parameters to parse_args
, $#
will always be 0 inside of it.
To get the desired result, change the last line to:
parse_args "$@"
The special variable "$@"
expands to the positional parameters of the current (top-level) scope as separate words. Subsequently they are passed to the invocation of parse_args
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With