I have a simple script where the first argument is reserved for the filename, and all other optional arguments should be passed to other parts of the script.
Using Google I found this wiki, but it provided a literal example:
echo "${@: -1}"
I can't get anything else to work, like:
echo "${@:2}"
or
echo "${@:2,1}"
I get "Bad substitution" from the terminal.
What is the problem, and how can I process all but the first argument passed to a bash script?
There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.
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.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs. However, Bash also supports Boolean expression conditions.
Use this:
echo "${@:2}"
The following syntax:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo
, but it matters for many other commands.
If you want a solution that also works in /bin/sh
try
first_arg="$1" shift echo First argument: "$first_arg" echo Remaining arguments: "$@"
shift [n]
shifts the positional parameters n times. A shift
sets the value of $1
to the value of $2
, the value of $2
to the value of $3
, and so on, decreasing the value of $#
by one.
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