bash 如何从shell脚本中获取倒数第二个参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11054939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the second last argument from shell script?
提问by Niek de Klein
I want to get the second last item given to a shell program. Currently I do it like this:
我想获得给 shell 程序的倒数第二个项目。目前我这样做:
file1_tmp="${@: -2}"
oldIFS=$IFS
IFS=" "
count=0
for value in $file1; do
if [[ count -e 0 ]]; then
file1=$value
fi
count=1
done
oldIFS=$IFS
I'm sure that there is a much easier way to do this. So how can I get the second last argument from a shell script input in as few lines as possible?
我相信有一种更简单的方法可以做到这一点。那么我怎样才能在尽可能少的行中从 shell 脚本输入中获取倒数第二个参数呢?
回答by Charles Duffy
set -- "first argument" "second argument" \
"third argument" "fourth argument" \
"fifth argument"
second_to_last="${@:(-2):1}"
echo "$second_to_last"
Note the quoting, which ensures that arguments with whitespace stick together -- which your original solution doesn't do.
请注意引用,它确保带有空格的参数粘在一起 - 您的原始解决方案不会这样做。
回答by Igor Chubin
In bash/ksh/zsh you can simply ${@: -2:1}
在 bash/ksh/zsh 中,您可以简单地 ${@: -2:1}
$ set a b c d
$ echo ${@: -1:1}
c
In POSIX sh you can use eval:
在 POSIX sh 中,您可以使用eval:
$ set a b c d
$ echo $(eval "echo $$(($#-2))")
c
回答by Andrew Clark
n=$(($#-1))
second_to_last=${!n}
echo "$second_to_last"
回答by Isaac
There are some options for all bash versions:
所有 bash 版本都有一些选项:
$ set -- aa bb cc dd ee ff
$ echo "${@: -2:1} ${@:(-2):1} ${@:(~1):1} ${@:~1:1} ${@:$#-1:1}"
ee ee ee ee ee
The (~) is the bitwise negation operator (search in the ARITHMETIC EVALUATION section).
It means flip all bits.
( ~) 是按位否定运算符(在 ARITHMETIC EVALUATION 部分中搜索)。
这意味着翻转所有位。
The selection even could be done with (integer) variables:
甚至可以使用(整数)变量进行选择:
$ a=1 ; b=-a; echo "${@:b-1:1} ${@:(b-1):1} ${@:(~a):1} ${@:~a:1} ${@:$#-a:1}"
ee ee ee ee ee
$ a=2 ; b=-a; echo "${@:b-1:1} ${@:(b-1):1} ${@:(~a):1} ${@:~a:1} ${@:$#-a:1}"
dd dd dd dd dd
For really old shells, you must use eval:
对于非常旧的 shell,您必须使用 eval:
eval "printf \"%s\n\" \"$$(($#-1))\""

