342

$1 is the first argument.
$@ is all of them.

How can I find the last argument passed to a shell script?

6
  • I was using bash, but the more portable solution the better.
    – Thomas
    Commented Dec 6, 2009 at 0:21
  • 7
    faqs.org/faqs/unix-faq/faq/part2/section-12.html
    – Inshallah
    Commented Dec 6, 2009 at 2:11
  • 10
    use can also use ${ !# } Commented Oct 6, 2015 at 11:43
  • 14
    For only bash, the Kevin Little's answer proposes the simple ${!#}. Test it using bash -c 'echo ${!#}' arg1 arg2 arg3. For bash, ksh and zsh, the Dennis Williamson's answer proposes ${@: -1}. Moreover ${*: -1} can also be used. Test it using zsh -c 'echo ${*: -1}' arg1 arg2 arg3. But that does not work for dash, csh and tcsh.
    – oHo
    Commented Jul 22, 2017 at 21:19
  • 3
    ${!#}, unlike ${@: -1}, also works with parameter expansion. You can test it with bash -c 'echo ${!#%.*}' arg1.out arg2.out arg3.out. Commented Aug 5, 2018 at 10:33

28 Answers 28

350

This is Bash-only:

echo "${@: -1}"
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
205

This is a bit of a hack:

for last; do true; done
echo $last

This one is also pretty portable (again, should work with bash, ksh and sh) and it doesn't shift the arguments, which could be nice.

It uses the fact that for implicitly loops over the arguments if you don't tell it what to loop over, and the fact that for loop variables aren't scoped: they keep the last value they were set to.

7
  • 10
    @MichałŠrajer, I think you meant colon and not comma ;) Commented Feb 26, 2013 at 8:24
  • 3
    @MichałŠrajer true is part of POSIX.
    – Rufflewind
    Commented Oct 9, 2015 at 5:35
  • 5
    With an old Solaris, with the old bourne shell (not POSIX), I have to write "for last in "$@"; do true; done"
    – mcoolive
    Commented Jan 25, 2016 at 10:47
  • 12
    @mcoolive @LaurenceGolsalves beside being more portable, for last in "$@"; do :; done also makes the intent much clearer. Commented Apr 23, 2018 at 18:59
  • 3
    @mcoolive: it even works in the unix v7 bourne shell from 1979. you can't get more portable if it runs on both v7 sh and POSIX sh :)
    – Dominik R
    Commented Nov 22, 2019 at 10:41
108
$ set quick brown fox jumps

$ echo ${*: -1:1} # last argument
jumps

$ echo ${*: -1} # or simply
jumps

$ echo ${*: -2:1} # next to last
fox

The space is necessary so that it doesn't get interpreted as a default value.

Note that this is bash-only.

4
  • 11
    Best answer, since it also includes the next to last arg. Thanks!
    – e40
    Commented Jul 7, 2013 at 0:54
  • 2
    Steven, I don't know what you did to land in the Penalty Box, but I am loving your work on here. Commented Sep 22, 2017 at 15:09
  • 4
    yes. simply the best. all but command and last argument ${@: 1:$#-1}
    – Dyno Fu
    Commented Jan 9, 2019 at 7:52
  • 1
    @DynoFu thank you for that, you answered my next question. So a shift might look like: echo ${@: -1} ${@: 1:$#-1}, where last becomes first and the rest slide down
    – Mike
    Commented Apr 18, 2019 at 19:46
81

The simplest answer for bash 3.0 or greater is

_last=${!#}       # *indirect reference* to the $# variable
# or
_last=$BASH_ARGV  # official built-in (but takes more typing :)

That's it.

$ cat lastarg
#!/bin/bash
# echo the last arg given:
_last=${!#}
echo $_last
_last=$BASH_ARGV
echo $_last
for x; do
   echo $x
done

Output is:

$ lastarg 1 2 3 4 "5 6 7"
5 6 7
5 6 7
1
2
3
4
5 6 7
5
  • 2
    $BASH_ARGV doesn't work inside a bash function (unless I'm doing something wrong). Commented Dec 28, 2014 at 15:46
  • 1
    The BASH_ARGV has the arguments when bash was called (or to a function) not the present list of positional arguments.
    – user8017719
    Commented Sep 20, 2018 at 21:55
  • Note also what BASH_ARGV will yield you is the value that the last arg that was given was, instead of simply "the last value". For example!: if you provide one single argument, then you call shift, ${@:$#} will produce nothing (because you shifted out the one and only argument!), however, BASH_ARGV will still give you that (formerly) last argument.
    – Steven Lu
    Commented Sep 24, 2018 at 20:13
  • Attention, ${!#} get nothing when execute script with sh XXX.sh 1 2 3
    – roamer
    Commented May 17, 2021 at 11:16
  • @roamer – This only works in bash (/bin/bash). You ran it through POSIX sh (/bin/sh), which on many systems is not bash.
    – Adam Katz
    Commented Mar 7, 2023 at 18:51
42

The following will work for you.

  • @ is for array of arguments.
  • : means at
  • $# is the length of the array of arguments.

So the result is the last element:

${@:$#} 

Example:

function afunction{
    echo ${@:$#} 
}
afunction -d -o local 50
#Outputs 50

Note that this is bash-only.

2
  • While the example is for a function, scripts also work the same way. I like this answer because it is clear and concise. Commented Oct 3, 2017 at 3:43
  • 1
    And it's not hacky. It uses explicit features of the language, not side effects or special qwerks. This should be the accepted answer.
    – musicin3d
    Commented Jan 5, 2018 at 16:09
36

Use indexing combined with length of:

echo ${@:${#@}} 

Note that this is bash-only.

2
  • 3
    echo $(@&$;&^$&%@^!@%^#**#&@*#@*#@(&*#_**^@^&(^@&*&@)
    – Atul
    Commented Feb 12, 2020 at 2:39
  • 2
    @Atul can you explain your interesting command? Commented Sep 16, 2021 at 7:57
31

Found this when looking to separate the last argument from all the previous one(s). Whilst some of the answers do get the last argument, they're not much help if you need all the other args as well. This works much better:

heads=${@:1:$#-1}
tail=${@:$#}

Note that this is bash-only.

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
26

This works in all POSIX-compatible shells:

eval last=\${$#}

Source: http://www.faqs.org/faqs/unix-faq/faq/part2/section-12.html

3
  • 2
    See this comment attached to an older identical answer. Commented Jul 13, 2012 at 12:21
  • 1
    The simplest portable solution I see here. This one has no security problem, @DennisWilliamson, the quoting empirically seems to be done right, unless there is a way to set $# to an arbitrary string (I don’t think so). eval last=\"\${$#}\" also works and is obviously correct. Don’t see why the quotes are not needed.
    – Palec
    Commented Oct 17, 2014 at 11:47
  • 1
    For bash, zsh, dash and ksh eval last=\"\${$#}\" is fine. But for csh and tcsh use eval set last=\"\${$#}\". See this example: tcsh -c 'eval set last=\"\${$#}\"; echo "$last"' arg1 arg2 arg3.
    – oHo
    Commented Jul 22, 2017 at 21:11
20

Here is mine solution:

  • pretty portable (all POSIX sh, bash, ksh, zsh) should work
  • does not shift original arguments (shifts a copy).
  • does not use evil eval
  • does not iterate through the whole list
  • does not use external tools

Code:

ntharg() {
    shift $1
    printf '%s\n' "$1"
}
LAST_ARG=`ntharg $# "$@"`
10
  • 1
    Great answer - short, portable, safe. Thanks! Commented Oct 7, 2016 at 9:45
  • 2
    This is a great idea, but I have a couple of suggestions: Firstly quoting should be added both around "$1" and "$#" (see this great answer unix.stackexchange.com/a/171347). Secondly, echo is sadly non-portable (particularly for -n), so printf '%s\n' "$1" should be used instead.
    – joki
    Commented Jan 4, 2018 at 9:37
  • thanks @joki I worked with many different unix systems and I wouldn't trust echo -n either, however I am not aware on any posix system where echo "$1" would fail. Anyhow, printf is indeed more predictable - updated. Commented Jan 9, 2018 at 14:11
  • 2
    Alternatively: last() { shift $(($# - 1));printf %s "$1";}
    – Léa Gris
    Commented Nov 19, 2020 at 15:03
  • 1
    @MichałŠrajer i Think if you are the guy tasked to write scripts for that 40 years old legacy SCO Unix, you are likely to know your way with the man pages and printed manual because browsing stackoverflow with Mozaic is going to be quite challenging on its own.
    – Léa Gris
    Commented Dec 2, 2020 at 13:20
11

From oldest to newer solutions:

The most portable solution, even older sh (works with spaces and glob characters) (no loop, faster):

eval printf "'%s\n'" "\"\${$#}\""

Since version 2.01 of bash

$ set -- The quick brown fox jumps over the lazy dog

$ printf '%s\n'     "${!#}     ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog     dog dog dog dog

For ksh, zsh and bash:

$ printf '%s\n' "${@: -1}    ${@:~0}"     # the space beetwen `:`
                                          # and `-1` is a must.
dog   dog

And for "next to last":

$ printf '%s\n' "${@:~1:1}"
lazy

Using printf to workaround any issues with arguments that start with a dash (like -n).

For all shells and for older sh (works with spaces and glob characters) is:

$ set -- The quick brown fox jumps over the lazy dog "the * last argument"

$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument

Or, if you want to set a last var:

$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument

And for "next to last":

$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog
10

If you are using Bash >= 3.0

echo ${BASH_ARGV[0]}
2
  • Also for next to last argument, do echo ${BASH_ARGV[1]}
    – Zombo
    Commented Feb 22, 2012 at 2:43
  • 1
    ARGV stands for "argument vector." Commented Aug 31, 2018 at 12:56
9

For bash, this comment suggested the very elegant:

echo "${@:$#}"

To silence shellcheck, use:

echo ${*:$#}

As a bonus, both also work in zsh.

5
shift `expr $# - 1`
echo "$1"

This shifts the arguments by the number of arguments minus 1, and returns the first (and only) remaining argument, which will be the last one.

I only tested in bash, but it should work in sh and ksh as well.

3
  • 12
    shift $(($# - 1)) - no need for an external utility. Works in Bash, ksh, zsh and dash. Commented Nov 9, 2010 at 2:32
  • @Dennis: Nice! I didn't know about the $((...)) syntax. Commented Nov 11, 2010 at 16:48
  • 1
    You'd want to use printf '%s\n' "$1" in order to avoid unexpected behaviour from echo (e.g. for -n).
    – joki
    Commented Jan 4, 2018 at 9:39
4

I found @AgileZebra's answer (plus @starfry's comment) the most useful, but it sets heads to a scalar. An array is probably more useful:

heads=( "${@: 1: $# - 1}" )
tail=${@:${#@}}

Note that this is bash-only.

Edit: Removed unnecessary $(( )) according to @f-hauri's comment.

3
  • How would you convert the heads into an array ?
    – Stephane
    Commented Dec 9, 2019 at 15:39
  • I already did by adding the parentheses, for example echo "${heads[-1]}" prints the last element in heads. Or am I missing something? Commented Dec 11, 2019 at 12:23
  • 1
    use of $(( )) is useless! "${@: 1 : $# - 1 }" will work same! Commented Dec 25, 2021 at 10:59
2

A solution using eval:

last=$(eval "echo \$$#")

echo $last
4
  • 7
    eval for indirect reference is overkill, not to mention bad practice, and a huge security concern (the value is not quote in echo or outside $(). Bash has a builtin syntax for indirect references, for any var: ! So last="${!#}" would use the same approach (indirect reference on $#) in a much safer, compact, builtin, sane way. And properly quoted.
    – MestreLion
    Commented Aug 7, 2011 at 16:28
  • See a cleaner way to perform the same in another answer.
    – Palec
    Commented Oct 17, 2014 at 11:23
  • @MestreLion quotes are not needed on the RHS of=.
    – Tom Hale
    Commented Jun 11, 2019 at 7:15
  • 1
    @TomHale: true for the particular case of ${!#}, but not in general: quotes are still needed if content contains literal whitespace, such as last='two words'. Only $() is whitespace-safe regardless of content.
    – MestreLion
    Commented Jun 18, 2019 at 21:23
2

If you want to do it in a non-destructive way, one way is to pass all the arguments to a function and return the last one:

#!/bin/bash

last() {
        if [[ $# -ne 0 ]] ; then
            shift $(expr $# - 1)
            echo "$1"
        #else
            #do something when no arguments
        fi
}

lastvar=$(last "$@")
echo $lastvar
echo "$@"

pax> ./qq.sh 1 2 3 a b
b
1 2 3 a b

If you don't actually care about keeping the other arguments, you don't need it in a function but I have a hard time thinking of a situation where you would never want to keep the other arguments unless they've already been processed, in which case I'd use the process/shift/process/shift/... method of sequentially processing them.

I'm assuming here that you want to keep them because you haven't followed the sequential method. This method also handles the case where there's no arguments, returning "". You could easily adjust that behavior by inserting the commented-out else clause.

2

For tcsh:

set X = `echo $* | awk -F " " '{print $NF}'`
somecommand "$X"

I'm quite sure this would be a portable solution, except for the assignment.

1
  • I know you posted this forever ago, but this solution is great - glad someone posted a tcsh one! Commented Feb 26, 2015 at 15:30
2

To return the last argument of the most recently used command use the special parameter:

$_

In this instance it will work if it is used within the script before another command has been invoked.

1
  • This is not what the question is asking
    – retnikt
    Commented Apr 8, 2020 at 8:07
1

After reading the answers above I wrote a Q&D shell script (should work on sh and bash) to run g++ on PGM.cpp to produce executable image PGM. It assumes that the last argument on the command line is the file name (.cpp is optional) and all other arguments are options.

#!/bin/sh
if [ $# -lt 1 ]
then
    echo "Usage: `basename $0` [opt] pgm runs g++ to compile pgm[.cpp] into pgm"
    exit 2
fi
OPT=
PGM=
# PGM is the last argument, all others are considered options
for F; do OPT="$OPT $PGM"; PGM=$F; done
DIR=`dirname $PGM`
PGM=`basename $PGM .cpp`
# put -o first so it can be overridden by -o specified in OPT
set -x
g++ -o $DIR/$PGM $OPT $DIR/$PGM.cpp
1

The following will set LAST to last argument without changing current environment:

LAST=$({
   shift $(($#-1))
   echo $1
})
echo $LAST

If other arguments are no longer needed and can be shifted it can be simplified to:

shift $(($#-1))
echo $1

For portability reasons following:

shift $(($#-1));

can be replaced with:

shift `expr $# - 1`

Replacing also $() with backquotes we get:

LAST=`{
   shift \`expr $# - 1\`
   echo $1
}`
echo $LAST
0
1
echo $argv[$#argv]

Now I just need to add some text because my answer was too short to post. I need to add more text to edit.

1
  • 1
    Which shell is this suppossed to work in? Not bash. Not fish (has $argv but not $#argv$argv[(count $argv)] works in fish). Commented Dec 16, 2014 at 16:02
1

This is part of my copy function:

eval echo $(echo '$'"$#")

To use in scripts, do this:

a=$(eval echo $(echo '$'"$#"))

Explanation (most nested first):

  1. $(echo '$'"$#") returns $[nr] where [nr] is the number of parameters. E.g. the string $123 (unexpanded).
  2. echo $123 returns the value of 123rd parameter, when evaluated.
  3. eval just expands $123 to the value of the parameter, e.g. last_arg. This is interpreted as a string and returned.

Works with Bash as of mid 2015.

2
  • The eval approach has been presented here many times already, but this one has an explanation of how it works. Could be further improved, but still worth keeping.
    – Palec
    Commented Aug 18, 2015 at 23:17
  • Just eval a="\$$#" will work without any echoes.
    – AnrDaemon
    Commented Dec 20, 2022 at 11:26
0
#! /bin/sh

next=$1
while [ -n "${next}" ] ; do
  last=$next
  shift
  next=$1
done

echo $last
1
  • This will fail if an argument is the empty string, but will work in 99.9% of the cases.
    – Thomas
    Commented Dec 6, 2009 at 0:10
0

Try the below script to find last argument

 # cat arguments.sh
 #!/bin/bash
 if [ $# -eq 0 ]
 then
 echo "No Arguments supplied"
 else
 echo $* > .ags
 sed -e 's/ /\n/g' .ags | tac | head -n1 > .ga
 echo "Last Argument is: `cat .ga`"
 fi

Output:

 # ./arguments.sh
 No Arguments supplied

 # ./arguments.sh testing for the last argument value
 Last Argument is: value

Thanks.

3
  • I suspect this would fail with ./arguments.sh "last value"
    – Thomas
    Commented Nov 5, 2013 at 3:25
  • Thank you for checking Thomas, I have tried to perform the as script like you mentinoed # ./arguments.sh "last value" Last Argument is: value is working fine now. # ./arguments.sh "last value check with double" Last Argument is: double Commented Nov 5, 2013 at 17:56
  • The problem is that the last argument was 'last value', and not value. The error is caused by the argument containing a space.
    – Thomas
    Commented Nov 8, 2013 at 3:02
0

There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.

  argArray=( "$@" )                        # Add all script arguments to argArray
  arrayLength=${#argArray[@]}              # Get the length of the array
  lastArg=$((arrayLength - 1))             # Arrays are zero based, so last arg is -1
  echo ${argArray[$lastArg]}

Sample output

$ ./lastarg.sh 1 2 buckle my shoe
shoe
0

Using parameter expansion (delete matched beginning):

args="$@"
last=${args##* }

It's also easy to get all before last:

prelast=${args% *}
3
  • Possible (poor) duplicate of stackoverflow.com/a/37601842/1446229
    – Xerz
    Commented Mar 17, 2018 at 23:30
  • This only works if the last argument does not contain a space.
    – Palec
    Commented Mar 18, 2018 at 16:49
  • Your prelast fails if the last argument is a sentence enclosed in double quotes, with said sentence supposed to be one argument.
    – Stephane
    Commented Dec 9, 2019 at 15:28
0
$ echo "${*: -1}"

That will print the last argument

1
  • This has already been mentioned in some other answers, such as this one.
    – Eric Aya
    Commented Aug 12, 2021 at 10:14
-2

Just use !$.

$ mkdir folder
$ cd !$ # will run: cd folder
1
  • 1
    This is not what the question is asking
    – retnikt
    Commented Apr 8, 2020 at 8:07

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