【问题标题】:Bash pass all arguments from function to command except for the last oneBash 将所有参数从函数传递到命令,除了最后一个
【发布时间】:2020-03-30 08:28:24
【问题描述】:
myfunc ()
{
    if [${*: -1} == "some argument"]
    then
        command anotherCommand "$@"
    elif [ ... ] 
        ...
    fi
}

如何更改"$@",使其将所有参数传递给anotherCommand除了最后一个?

【问题讨论】:

  • 为什么不改变接口,让要检查的参数是第一个参数?

标签: bash arguments parameter-passing


【解决方案1】:

您可以将脚本更改为:

myfunc ()
{
    if [${*: -1} == "some argument"]
    then
        command anotherCommand "${@:1:$#-1}"
    elif [ ... ] 
        ...
    fi
}

你将有效地弹出最后一个参数。

示例:

#!/bin/bash


myfunc ()
{
    echo "${@:1:$#-1}"
}

myfunc apple orange banana watermelon

打印

$ ./some.sh 
apple orange banana

【讨论】:

  • 您的答案是弹出第一个和最后一个参数。您可以通过bash -c 'echo "${@:1:$#-1}"' arg1 arg2 arg3 arg4 --> arg2 arg3 验证这一点
  • cat 1.sh if [[ $1 == "1" ]];然后 echo $@ else echo "${@:1:$#-1}" fi bash 1.sh 11 22 33 11 22 bash 1.sh 1 22 33 1 22 33
  • @AdamGriffiths 我添加了一个可以在终端中运行的示例。它为我工作。让我知道它是否有效
  • @AdamGriffiths 如果你这样做 bash -c 'echo $@' arg1 arg2 你可以看到它会丢弃 arg1
  • @AdamGriffiths 我认为这可能是因为第一个参数通常是当前进程的路径,并且对于函数是不同的。但我不确定。有人可能会纠正。
【解决方案2】:

更改myfunc,让关键参数出现在第一个,然后你可以简单地写

myfunc () {
   first=$1
   shift
   if [ "$first" = "some argument" ]; then
       command anotherCommand "$@"
   elif [ ... ]; then
       ...
   fi
}

或者,如果出于某种原因您需要在以后的分支中使用 $@ 中的所有原始参数,您可以将 shift 移动到 if 语句中:

if [ "$first" == "some argument" ]; then
    shift
    command anotherCommand "$@"
elif ...

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2019-03-26
    • 2013-04-12
    • 1970-01-01
    • 2021-11-25
    • 2018-01-05
    • 1970-01-01
    • 2013-12-14
    • 2021-04-30
    相关资源
    最近更新 更多