Getting the last argument passed to a shell script

2019-01-05 07:20发布

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

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

26条回答
手持菜刀,她持情操
2楼-- · 2019-01-05 07:47

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楼-- · 2019-01-05 07:48
#! /bin/sh

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

echo $last
查看更多
混吃等死
4楼-- · 2019-01-05 07:49

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.

查看更多
迷人小祖宗
5楼-- · 2019-01-05 07:50
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.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-05 07:54

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=${@:$#}
查看更多
爷、活的狠高调
7楼-- · 2019-01-05 07:54

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
查看更多
登录 后发表回答