1

In a bash script file, is there a way that I can use command line arguments from within a function which has parameters?

Or do I need to assign all command line parameters to a variable for them to be accessible in the function body?


echo $1   # may be "abc"

function f() { $1; }   # will be "def", but I need "abc" here

f "def"

PS: I found a similar question on stack overflow, but that question doesn't deal with the issue I describe here?

2
  • 1
    Just use f "$1" Commented May 26, 2021 at 15:14
  • 2
    AFAIK, there isn't a way to access the script-level command line arguments from within a shell function. The meanings of $1, $@ and $* are overridden in the function by the function's context. You could create an array outside the function containing the command-line arguments – args=("$@") — and reference that within the function. Commented May 26, 2021 at 15:15

2 Answers 2

1

Just for the record, this is possible in extdebug mode through BASH_ARGC and BASH_ARGV variables, but populating a global array with positional parameters is much easier than that, and has no side-effects.

$ bash -O extdebug -s foo bar
$ f() {
>   declare -p BASH_ARGC BASH_ARGV
>   echo ${BASH_ARGV[BASH_ARGC[0] + BASH_ARGC[1] - 1]}
> }
$ f 42 69
declare -a BASH_ARGC=([0]="2" [1]="2")
declare -a BASH_ARGV=([0]="69" [1]="42" [2]="bar" [3]="foo")
foo
Sign up to request clarification or add additional context in comments.

Comments

1
SCRIPT_ARG=$1

function f() { 
  FUNC_ARG=$1; 

  echo $SCRIPT_ARG # Prints "abc"
  echo $FUNC_ARG   # Prints "def"

}

f "def"

Comments

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.