How to get the n
th positional argument in Bash, where n
is variable?
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
$# is a special variable in bash , that expands to the number of arguments (positional parameters) i.e. $1, $2 ... passed to the script in question or the shell in case of argument directly passed to the shell e.g. in bash -c '...' .... . This is similar to argc in C.
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0 . Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command.
-n is one of the string operators for evaluating the expressions in Bash. It tests the string next to it and evaluates it as "True" if string is non empty. Positional parameters are a series of special variables ( $0 , $1 through $9 ) that contain the contents of the command line argument to the program.
Use Bash's indirection feature:
#!/bin/bash n=3 echo ${!n}
Running that file:
$ ./ind apple banana cantaloupe dates
Produces:
cantaloupe
Edit:
You can also do array slicing:
echo ${@:$n:1}
but not array subscripts:
echo ${@[n]} # WON'T WORK
If N
is saved in a variable, use
eval echo \${$N}
if it's a constant use
echo ${12}
since
echo $12
does not mean the same!
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