Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all elements of a bash array except the first

Tags:

arrays

bash

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?

like image 222
grok12 Avatar asked Jun 09 '11 02:06

grok12


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

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 you display the first element of an array in bash?

To get the first element (10) from the array, we can use the subscript [ ] syntax by passing an index 0 . In bash arrays are zero-indexed, so the first element index is 0 .

Do bash arrays start at 0 or 1?

bash arrays start at index position 0.


Video Answer


2 Answers

$ a=(1 2 3) $ echo "${a[@]:1}" 2 3 
like image 78
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 22:09

Ignacio Vazquez-Abrams


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).

like image 20
Tom Hale Avatar answered Sep 28 '22 21:09

Tom Hale