14

I am looking to find the last positional parameter. I know to find the number of parameters is $# which logically is the last but I need to find and use what is in the last positional parameter.

It would be like if $# = 5, I want to do $5.

I have tried to do something like $$# or ${$#} as guesses but can't get it.

Instances where I would need to use it is in an if statement or declaring it to another variable or with echo.

I hope that is clear. Thanks in advance.

1
  • Is this for a shell function or are you trying to get the last argument on the previous command line?
    – sarnold
    Commented Apr 2, 2012 at 2:26

3 Answers 3

21

You want ${!#}, which combines the argument count with indirection.

3
  • 2
    and eval last=\$$# for shells that lack indirection via !.
    – Idelic
    Commented Apr 2, 2012 at 17:53
  • This seems to be what I am looking for. Thank you.
    – leeman24
    Commented Apr 3, 2012 at 0:04
  • And I am guessing you can't assign t${!#} as a variable if thats what you meant. But eval last=\$$# worked for me. I think thats what you meant by lack of indirection
    – leeman24
    Commented Apr 3, 2012 at 0:15
13

This seems like a more direct approach:

${@: -1}

Some further information here. I'm not sure about portability outside of Bash.

1
  • Do not forget the space between colon (:) and minus (-), or yo'u'll get another behavior/command. In this way, you are defining a default parameter to $@ of it is null or unset. Commented Feb 15, 2023 at 15:46
5

Here is another way:

while [[ "$1" != "" ]];do
    last_parm=$1
    shift
done
echo $last_parm

Give a test:

$ ./test.sh 1 2 3 4 5
5
1
  • 2
    It is VERY important to note that this method eliminates all positional parameters, and makes all but the last inaccessible. While in the limited context of the question this is a correct answer, in practice it will have undesirable side-effects for many realistic scenarios. This approach is only acceptable as-is if you really don't care about anything but the last parameter.
    – zacronos
    Commented Aug 25, 2018 at 13:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.