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.

8
  • 73
    For those (like me) wondering why is the space needed, man bash has this to say about it: > Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.
    – foo
    Commented May 28, 2015 at 3:34
  • 1
    I've been using this and it breaks in MSYS2 bash in windows only. Bizarre.
    – Steven Lu
    Commented Mar 23, 2018 at 18:25
  • 3
    Note: This answer works for all Bash arrays, unlike ${@:$#} which only works on $@. If you were to copy $@ to a new array with arr=("$@"), ${arr[@]:$#} would be undefined. This is because $@ has a 0th element that isn't included in "$@" expansions.
    – Mr. Llama
    Commented Mar 18, 2019 at 17:26
  • 1
    @Mr.Llama: Another place to avoid $# is when iterating over arrays since, in Bash, arrays are sparse and while $# will show the number of elements in the array it's not necessarily pointing to the last element (or element+1). In other words, one shouldn't do for ((i = 0; i++; i < $#)); do something "${array[$i]}"; done and instead do for element in "${array[@]}"; do something "$element"; done or iterate over the indices: for index in "${!array[@]}"; do something "$index" "${array[$index]}"; done if you need to do something with the values of the indices. Commented Mar 18, 2019 at 17:38
  • Works for Bourne shell also, at least for me
    – GregD
    Commented Apr 5, 2021 at 19:50