grok12
grok12

Reputation: 3666

Getting all elements of a bash array except the first

I have an indexed bash array and I'd like to use an expression like "${a[@]}" except I want it to not include a[0]. The best that I can think of is this:

j=0
for i in "${a[@]}"
do
    b[j]=${a[++j]}
done

and then use "${b[@]}". Is there a better way?

Upvotes: 42

Views: 27265

Answers (2)

Tom Hale
Tom Hale

Reputation: 46765

If it's a standard array, use:

"${a[@]:1}"

If you're working with parameters:

"${@:2}"

Note the different syntax and that $@ is 1-indexed (since $0 is the name of the script).

Upvotes: 11

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

$ a=(1 2 3)
$ echo "${a[@]:1}"
2 3

Upvotes: 70

Related Questions