Bash:获取第一个命令行参数并传递其余部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10569198/
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
Bash: Take the first command line argument and pass the rest
提问by user554005
Example:
例子:
check_prog hostname.com /bin/check_awesome -c 10 -w 13
check_prog hostname.com /bin/check_awesome -c 10 -w 13
check_remote -H $HOSTNAME -C "$ARGS"
#To be expanded as
check_remote -H hostname.com -C "/bin/check_awesome -c 10 -w 13"
I hope the above makes sense, The arguments will change as I will be using this for about 20+ commands. Its a odd method of wrapping a program, but its to work around A few issues with a few systems we are using here (Gotta love code from the 70s)
我希望以上内容是有道理的,参数会改变,因为我将在大约 20 多个命令中使用它。这是一种包装程序的奇怪方法,但它可以解决我们在这里使用的一些系统的一些问题(必须喜欢 70 年代的代码)
The above could be written in perl or python, but Bash would be the preferred method
以上可以用 perl 或 python 编写,但 Bash 将是首选方法
回答by ravi
You can use shift
您可以使用移位
shift is a shell builtin that operates on the positional parameters. Each time you invoke shift, it "shifts" all the positional parameters down by one. $2 becomes $1, $3 becomes $2, $4 becomes $3, and so on
shift 是一个 shell 内置函数,它对位置参数进行操作。每次调用 shift 时,它都会将所有位置参数“向下移动”一个。2 美元变成 1 美元,3 美元变成 2 美元,4 美元变成 3 美元,依此类推
example:
例子:
$ function foo() { echo $@; shift; echo $@; }
$ foo 1 2 3
1 2 3
2 3
回答by Abdullah
As a programmer I would strongly recommend against shift
because operations that modify the state can affect large parts of a script and make it harder to understand, modify, and debug:sweat_smile:. You can instead use the following:
作为一名程序员,我强烈建议不shift
要这样做,因为修改状态的操作会影响脚本的大部分内容,并使其更难理解、修改和调试:sweat_smile:。您可以改为使用以下内容:
#!/usr/bin/env bash
all_args=("$@")
first_arg=
second_args=
rest_args=("${all_args[@]:2}")
echo "${rest_args[@]}"