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]}?

6
  • At least for bash: "echo "${@: -1}" (Mind the space)"
    – muru
    Commented Oct 29, 2018 at 9:34
  • Cheers @muru. Even better would be: echo "${*: -1}" which shellcheck won't complain about.
    – Tom Hale
    Commented Oct 29, 2018 at 9: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
    Commented Oct 29, 2018 at 10:04
  • @ikkachu I was wrong about shellcheck. I prefer your "${@:$#}" as most readable. Cheers!
    – Tom Hale
    Commented Oct 29, 2018 at 10:21
  • "${@:$#}" is not portable like all similar constructs. If shellcheck is intended to mark non-POSIX syntax, it should complain.
    – schily
    Commented Oct 29, 2018 at 11:25

1 Answer 1

5

ilkkachu suggested the very readable:

echo "${@:$#}"
5
  • @ilkkachu Thanks for the edit - sorry for getting your name wrong.
    – Tom Hale
    Commented Dec 17, 2018 at 8: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
    Commented Dec 17, 2018 at 11:24
  • @TomHale This raises SC2124 ( github.com/koalaman/shellcheck/wiki/SC2124 ): "Assigning an array to a string".
    – Johannes
    Commented Feb 11, 2019 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
    Commented Feb 11, 2019 at 23:18
  • @TomHale, switching to ${*:$#} gets rid of the shellcheck warning.
    – Lucas
    Commented Feb 16, 2021 at 0:02

Not the answer you're looking for? Browse other questions tagged .