Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: all of array except last element

Tags:

bash

Bash has a neat way of giving all elements in an array except the first:

"${a[@]:1}"           

To get all except the last I have found:

"${a[@]:0:$((${#a[@]}-1))}"

But, man, that is ugly.

Is there an elegant alternative?

like image 688
Ole Tange Avatar asked Jul 06 '17 04:07

Ole Tange


People also ask

How to remove last element in array bash?

To remove the last element (b) from an above array, we can use the built-in unset command followed by the arr[-1] in bash.

Is not equal to in bash?

The not equal function in Ubuntu bash is denoted by the symbol “-ne,” which would be the initial character of “not equal.” Also included is the “! =” operator that is used to indicate the not equal condition.

How do I split a string in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How do I index an array in bash?

To access elements of array using index in Bash, use index notation on the array variable as array[index].


1 Answers

I am not sure how much improvement it would be, but you can drop the arithmetic operator ($(())) and starting index (0 here):

${a[@]::${#a[@]}-1}

So:

$ foo=( 1 2 3 )

$ echo "${foo[@]::${#foo[@]}-1}"
1 2

As you can see, the improvement is purely syntactical; the idea remains the same.

like image 147
heemayl Avatar answered Oct 01 '22 09:10

heemayl