How to access command line arguments of the caller inside a function? How to access command line arguments of the caller inside a function? bash bash

How to access command line arguments of the caller inside a function?


If you want to have your arguments C style (array of arguments + number of arguments) you can use $@ and $#.

$# gives you the number of arguments.
$@ gives you all arguments. You can turn this into an array by args=("$@").

So for example:

args=("$@")echo $# arguments passedecho ${args[0]} ${args[1]} ${args[2]}

Note that here ${args[0]} actually is the 1st argument and not the name of your script.


My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV,although it talks about "the stack" a lot.

#!/bin/bashshopt -s extdebugfunction argv {  for a in ${BASH_ARGV[*]} ; do    echo -n "$a "  done  echo}function f {  echo f $1 $2 $3  echo -n f ; argv}function g {  echo g $1 $2 $3  echo -n g; argv  f}f boo bar bazg goo gar gaz

Save in f.sh

$ ./f.sh arg0 arg1 arg2f boo bar bazfbaz bar boo arg2 arg1 arg0g goo gar gazggaz gar goo arg2 arg1 arg0ffgaz gar goo arg2 arg1 arg0


#!/usr/bin/env bashecho name of script is $0echo first argument is $1echo second argument is $2echo seventeenth argument is $17echo number of arguments is $#

Edit: please see my comment on question