处理除第一个之外的所有参数(在bash脚本中)

本文翻译自:Process all arguments except the first one (in a bash script)

I have a simple script where the first argument is reserved for the filename, and all other optional arguments should be passed to other parts of the script. 我有一个简单的脚本,其中第一个参数是为文件名保留的,所有其他可选参数应该传递给脚本的其他部分。

Using Google I found this wiki , but it provided a literal example: 使用Google我发现了这个wiki ,但它提供了一个文字示例:

echo "${@: -1}"

I can't get anything else to work, like: 我无法得到任何其他工作,例如:

echo "${@:2}"

or 要么

echo "${@:2,1}"

I get "Bad substitution" from the terminal. 我从终端得到“坏替换”。

What is the problem, and how can I process all but the first argument passed to a bash script? 问题是什么,除了传递给bash脚本的第一个参数外,我该如何处理?


#1楼

参考:https://stackoom.com/question/c0Et/处理除第一个之外的所有参数-在bash脚本中


#2楼

Use this: 用这个:

echo "${@:2}"

The following syntax: 以下语法:

echo "${*:2}"

would work as well, but is not recommended, because as @Gordon already explained, that using * , it runs all of the arguments together as a single argument with spaces, while @ preserves the breaks between them (even if some of the arguments themselves contain spaces). 也可以工作,但不推荐,因为正如@Gordon已经解释的那样,使用* ,它将所有参数作为单个参数与空格一起运行,而@保留它们之间的中断(即使一些参数本身包含空格)。 It doesn't make the difference with echo , but it matters for many other commands. 它与echo没有区别,但它对许多其他命令很重要。


#3楼

If you want a solution that also works in /bin/sh try 如果你想要一个也适用于/bin/sh的解决方案

first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"

shift [n] shifts the positional parameters n times. shift [n]将位置参数移位n次。 A shift sets the value of $1 to the value of $2 , the value of $2 to the value of $3 , and so on, decreasing the value of $# by one. shift$1的值设置为$2的值, $2的值设置为$3 ,依此类推,将$#的值$# 1。


#4楼

http://wiki.bash-hackers.org/scripting/posparams http://wiki.bash-hackers.org/scripting/posparams

It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage 它解释了shift的使用(如果你想丢弃前N个参数)然后实现批量使用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值