Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

3
  • 3
    The Steven Penny's answer is a bit nicer: use ${@: -1} for last and ${@: -2:1} for second last (and so on...). Example: bash -c 'echo ${@: -1}' prog 0 1 2 3 4 5 6 prints 6. To stay with this current AgileZebra's approach, use ${@:$#-1:1} to get the second last. Example: bash -c 'echo ${@:$#-1:1}' prog 0 1 2 3 4 5 6 prints 5. (and ${@:$#-2:1} to get the third last and so on...)
    – oHo
    Commented Nov 26, 2015 at 8:05
  • 4
    AgileZebra's answer supplies a way of getting all but the last arguments so I wouldn't say Steven's answer supersedes it. However, there seems to be no reason to use $((...)) to subtract the 1, you can simply use ${@:1:$# - 1}.
    – dkasak
    Commented Nov 4, 2016 at 20:02
  • Thanks dkasak. Updated to reflect your simplification.
    – AgileZebra
    Commented Jun 8, 2020 at 11:06