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:54

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
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-05 07:56

Use indexing combined with length of:

echo ${@:${#@}} 
查看更多
地球回转人心会变
4楼-- · 2019-01-05 07:57

A solution using eval:

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

echo $last
查看更多
再贱就再见
5楼-- · 2019-01-05 07:59

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 $# "$@"`
查看更多
闹够了就滚
6楼-- · 2019-01-05 07:59

This format can worked in Slackware and Cygwin.

"${x[@]:(-1)}", if used with $@, "${@:(-1)}"

It means is: ${@:(N)}, will return all element after N index.(include N), -1 is thelast.

查看更多
一夜七次
7楼-- · 2019-01-05 08:00

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