公告
财富商城
积分规则
提问
发文
2019-01-05 07:20发布
趁早两清
$1 is the first argument. $@ is all of them.
$1
$@
How can I find the last argument passed to a shell script?
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.
$ 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 doesnt get interpreted as a default value.
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.
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
heads=( "${@:1:$(($# - 1))}" ) tail=${@:${#@}}
If you are using Bash >= 3.0
echo ${BASH_ARGV[0]}
This is part of my copy function:
eval echo $(echo '$'"$#")
To use in scripts, do this:
a=$(eval echo $(echo '$'"$#"))
Explanation (most nested first):
$(echo '$'"$#")
$[nr]
[nr]
$123
echo $123
eval
last_arg
Works with Bash as of mid 2015.
最多设置5个标签!
Now I just need to add some text because my answer was too short to post. I need to add more text to edit.
The space is necessary so that it doesnt get interpreted as a default value.
For tcsh:
I'm quite sure this would be a portable solution, except for the assignment.
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:If you are using Bash >= 3.0
This is part of my copy function:
To use in scripts, do this:
Explanation (most nested first):
$(echo '$'"$#")
returns$[nr]
where[nr]
is the number of parameters. E.g. the string$123
(unexpanded).echo $123
returns the value of 123rd parameter, when evaluated.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.