0

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?

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
AxD
  • 2,714
  • 3
  • 31
  • 53
  • Just use `f "$1"` – anubhava May 26 '21 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. – Jonathan Leffler May 26 '21 at 15:15

2 Answers2

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
oguz ismail
  • 1
  • 16
  • 47
  • 69
0
SCRIPT_ARG=$1

function f() { 
  FUNC_ARG=$1; 

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

}

f "def"
Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74