Inside a function, $1 ... $n
are the parameters passed to that function. Outside a function $1 ... $n
are the parameters passed to the script.
Can I somehow access the parameters passed to the script inside a function?
Using arguments Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1 , $2 , and so on. The $0 will contain the script name.
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=("$@") .
We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements. Using getopts, we can assign the positional arguments/ parameters from the command line to the bash variables directly.
Usually you just pass them as parameters to the function at call time.
The (uglier) alternative is to put them in global variables.
(I know this is an old post, but none of the answers actually answered the question.)
Use the BASH_ARGV array. It contains the arguments passed to the invoking script in reverse order (i.e., it's a stack with the top at index 0). You may have to turn on extended debugging in the shebang (e.g., #!/bin/bash -O extdebug
) or with shopt
(e.g., shopt -s extdebug
), but it works for me in bash 4.2_p37 without it turned on.
From man bash
:
An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging mode….
Here's a function I use to print all arguments in order on a single line:
# Print the arguments of the calling script, in order. function get_script_args { # Get the number of arguments passed to this script. # (The BASH_ARGV array does not include $0.) local n=${#BASH_ARGV[@]} if (( $n > 0 )) then # Get the last index of the args in BASH_ARGV. local n_index=$(( $n - 1 )) # Loop through the indexes from largest to smallest. for i in $(seq ${n_index} -1 0) do # Print a space if necessary. if (( $i < $n_index )) then echo -n ' ' fi # Print the actual argument. echo -n "${BASH_ARGV[$i]}" done # Print a newline. echo fi }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With