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
  • 28,728
  • 32
  • 139
  • 229
  • At least for bash: ["`echo "${@: -1}"` (Mind the space)"](https://unix.stackexchange.com/a/437050/70524) – muru Oct 29 '18 at 09:34
  • Cheers @muru. Even better would be: `echo "${*: -1}"` which `shellcheck` won't complain about. – Tom Hale Oct 29 '18 at 09:53
  • @TomHale, hmm, I don't get a complaint for `echo "${@: -1}"`. What does it complain to you about? I'd go with `"${@: -1}"` (or `"${@:$#}"`) just because `"$@"` is so much more common. Seeing `"$*"` makes me stop and think what the code is doing... – ilkkachu Oct 29 '18 at 10:04
  • @ikkachu I was wrong about `shellcheck`. I prefer your `"${@:$#}"` as most readable. Cheers! – Tom Hale Oct 29 '18 at 10:21
  • "${@:$#}" is not portable like all similar constructs. If `shellcheck` is intended to mark non-POSIX syntax, it should complain. – schily Oct 29 '18 at 11:25
  • @schily shellcheck has sh, ksh and bash modes. – Tom Hale Oct 30 '18 at 08:40

1 Answers1

5

ilkkachu suggested the very readable:

echo "${@:$#}"
ilkkachu
  • 133,243
  • 15
  • 236
  • 397
Tom Hale
  • 28,728
  • 32
  • 139
  • 229
  • @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