如何通过除一个(不是第一个/最后一个)命令行参数之外的所有参数,而不会丢失引用?

时间:2018-01-28 17:59:41

标签: bash

我有一个名为as的脚本:

myscript "first argument" "second argument" "third argument" ...

我想从该脚本中调用函数:

anotherFunction "first argument" "third argument" ...

我尝试使用$@转换echo,但报价不断丢失。我目前的尝试看起来如下,但它不起作用;使用错误的参数调用anotherFunction

delete() {
    commandLine=`echo "$commandLine" | sed "s|$1||"`
}
anotherFunction() {
    echo "Called with first argument:  $1"
    echo "Called with second argument: $2"
}

# shown as a function here so it can be copied and pasted to test
# works the same way when it's actually an external script
myscript() {
  commandLine="$@"
  delete $2
  anotherFunction $commandLine
}

myscript "first argument" "second argument" "third argument"

想要的输出是:

Called with first argument:  first argument
Called with second argument: third argument

......而是它的发光:

Called with first argument:  first
Called with second argument: argument

1 个答案:

答案 0 :(得分:3)

如果您的目标是让myScript "foo" "bar" "hello world"运行anotherFunction "foo" "hello world" - 删除第二个参数 - 将如下所示:

args=( "$1" "${@:3}" )
anotherFunction "${args[@]}"

你也可以把它写成:

args=( "$@" )
unset args[1]
anotherFunction "${args[@]}"