Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 $* 
like image 490
DonGar Avatar asked Apr 29 '10 21:04

DonGar


People also ask

How do I access command line arguments?

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.

How do you access arguments within a script?

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.

How do I access command line arguments in Linux?

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.


1 Answers

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.

like image 101
stigi Avatar answered Sep 29 '22 08:09

stigi