Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash argument parsing in function

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
like image 635
Heinrich Avatar asked Sep 06 '14 17:09

Heinrich


People also ask

How does bash parse arguments?

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.

How do you pass an argument to a function in shell 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.

How do I parse a command-line in bash?

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.


1 Answers

$# 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.

like image 92
David Foerster Avatar answered Sep 20 '22 13:09

David Foerster