27

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?

1
  • 6
    You can hack with b=("${a[@]}"); unset "b[-1]"; do_whatever_with "${b[@]}" Commented Jul 6, 2017 at 4:35

1 Answer 1

36

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note for zsh users: the simplification works if you keep the starting index.

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.