Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ${@:-1} return the last element of $@?

Tags:

bash

I thought to post up a Q&A on this as I did not find anything similar. If it already exists, please mark this as a duplicate.


The following code, running under Bash shell, doesn't work (should return just f, the last (-1-th) item in $@):

$ set -- a b c d e f
$ echo ${@:-1}
a b c d e f
like image 402
Zaid Avatar asked Oct 16 '16 17:10

Zaid


People also ask

How do I return the last element in a list?

To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

How do you return the last element in an ArrayList?

The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1) , so you would use myArrayList. get(myArrayList. size()-1) to retrieve the last element.

How do I get the last element in Python?

The best way to get the last element of a list in Python is using the list[-1]. Python allows you to use negative indices, which count from the end of the list instead of the beginning. So list[-1] gets the last element, list[-2] gets the second to last.

How can the last element of a set be deleted?

The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. The last element of the Set can be deleted by by passing its iterator.


2 Answers

${parameter:-word} is a type of parameter expansion:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.


So ${@:-1} is interpreted as:

  • If $@ is unset or null, substitute with 1
  • Else leave $@ as it is

Since the latter is true, echo prints $@ in all its glory


The Fix:

Put some space between : and -:

$ echo ${@: -1}
f
like image 110
Zaid Avatar answered Oct 19 '22 12:10

Zaid


As an alternative syntax to the space suggested by Zaid, you can also use round brackets to get the functionality you want:

echo ${@:(-1)}

f

like image 10
spinup Avatar answered Oct 19 '22 14:10

spinup