Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process all arguments except the first one (in a bash script)

Tags:

bash

shell

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?

like image 565
theta Avatar asked Jan 29 '12 22:01

theta


People also ask

What is the difference between $@ and $* in bash?

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.

What is $@ in bash?

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.

How do I pass multiple arguments to a shell script?

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 …

Is bash 1 True or false?

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.


2 Answers

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.

like image 189
Oliver Charlesworth Avatar answered Sep 22 '22 17:09

Oliver Charlesworth


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.

like image 34
Ben Jackson Avatar answered Sep 21 '22 17:09

Ben Jackson