I'm attempting to write a function in bash that will access the scripts command line arguments, but they are replaced with the positional arguments to the function. Is there any way for the function to access the command line arguments if they aren't passed in explicitly?
# Demo function function stuff { echo $0 $* } # Echo's the name of the script, but no command line arguments stuff # Echo's everything I want, but trying to avoid stuff $*
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
Using '$@' for reading command-line arguments: The command-line arguments can be read without using argument variables or getopts options. Using '$@' with the first bracket is another way to read all command-line argument values.
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 passed echo ${args[0]} ${args[1]} ${args[2]}
Note that here ${args[0]}
actually is the 1st argument and not the name of your script.
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