1

If I do:

set a b c

How do I access the last element of $@, namely c?

I've initially thought to subscript the $@ array:

"${@[$#-1]}"

But:

bash: ${@[$#-1]}: bad substitution

I eventually came up with:

eval echo "\$$#"

Is there a way to get the last element of $@ without eval?

Is the only way to first copy it to another array and access ${copy[-1]}?

Tom Hale
  • 30,455

1 Answers1

5

ilkkachu suggested the very readable:

echo "${@:$#}"
ilkkachu
  • 138,973
Tom Hale
  • 30,455
  • @ilkkachu Thanks for the edit - sorry for getting your name wrong. – Tom Hale Dec 17 '18 at 08:18
  • Well, everyone seems to get it wrong here :D (the ell does get a bit hidden within the vertical lines). So, no problem. – ilkkachu Dec 17 '18 at 11:24
  • @TomHale This raises SC2124 ( https://github.com/koalaman/shellcheck/wiki/SC2124 ): "Assigning an array to a string". – Johannes Feb 11 '19 at 17:44
  • 1
    @Johannnes that warning seems redundant. If it's a one element array, and can only ever be one element, what exactly is the issue? I've raised some issues with shellcheck in the past, and sheet you do so in this case. What does it say with * instead? – Tom Hale Feb 11 '19 at 23:18
  • @TomHale, switching to ${*:$#} gets rid of the shellcheck warning. – Lucas Feb 16 '21 at 00:02