6

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
3
  • I now the reason for the 'output 0' but is there a way to do the argument parsing in an extra function? Commented Sep 6, 2014 at 17:37
  • Add $@ after parse_args . Commented Sep 6, 2014 at 17:45
  • thx Cyrus. Solution: parse_args $@ Commented Sep 6, 2014 at 17:49

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answers. And great example you added to my answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.