45

If you have a list in python, and you want the elements from 2 to n can do something nice like

list[2:]

I'd like to something similar with argv in Bash. I want to pass all the elements from $2 to argc to a command. I currently have

command $2 $3 $4 $5 $6 $7 $8 $9

but this is less than elegant. Would would be the "proper" way?

3 Answers 3

77

you can do "slicing" as well, $@ gets all the arguments in bash.

echo "${@:2}"

gets 2nd argument onwards

eg

$ cat shell.sh
#!/bin/bash
echo "${@:2}"

$ ./shell.sh 1 2 3 4
2 3 4
Sign up to request clarification or add additional context in comments.

3 Comments

You should also wrap it in double-quotes to avoid problems with spaces in arguments (e.g. echo "${@:2}" would work properly when called with ./shell.sh 1 2 "multi-word argument" 4 5).
Worth noting that this supports length as well, i.e. "${@:start:len}"
Can you also give a default value if ${@:2} is empty?
4

Store $1 somewhere, then shift and use $@?

1 Comment

good suggestion, but i think an operation on a list would be more elegant
4

script1.sh:

#!/bin/bash
echo "$@"

script2.sh:

#!/bin/bash
shift
echo "$@"

$ sh script1.sh 1 2 3 4
1 2 3 4 
$ sh script2.sh 1 2 3 4 
2 3 4

2 Comments

This is a great solution, in particular to get subcommands options!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.