获取第一个命令行参数并传递其余的参数

例如:

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"

我希望以上说得通。参数将发生变化,因为我将在大约20多个命令中使用这个参数。这是一种包装程序的奇怪方法,但是它解决了我们在这里使用的一些系统的一些问题(我喜欢70年代的代码)。

上面的代码可以用 Perl 或 Python 编写,但是 Bash 将是首选的方法。

59139 次浏览

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

example:

$ function foo() { echo $@; shift; echo $@; }
$ foo 1 2 3
1 2 3
2 3

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:

#!/usr/bin/env bash


all_args=("$@")
first_arg="$1"
second_args="$2"
rest_args=("${all_args[@]:2}")


echo "${rest_args[@]}"

Adapting Abdullah's answer a bit:

your_command "$1" "${@:2}"

Tested on Bash (v3.2 and v5.1) and Zsh (v5.8)