将参数附加到参数列表

将参数附加到参数列表

我有以下 Bash 代码:

function suman {

    if test "$#" -eq "0"; then
        echo " [suman] using suman-shell instead of suman executable.";
        suman-shell "$@"
    else
        echo "we do something else here"
    fi

}


function suman-shell {

    if [ -z "$LOCAL_SUMAN" ]; then
        local -a node_exec_args=( )
        handle_global_suman node_exec_args "$@"
    else
        NODE_PATH="${NEW_NODE_PATH}" PATH="${NEW_PATH}" node "$LOCAL_SUMAN" --suman-shell "$@";
    fi
}

suman用户在不带参数的情况下执行命令时,会出现以下情况:

  echo " [suman] using suman-shell instead of suman executable.";
  suman-shell "$@"

我的问题是 - 如何将参数附加到“$@”值?我需要简单地做类似的事情:

handle_global_suman node_exec_args "--suman-shell $@"

显然这是错误的,但我不知道该怎么做。我是什么不是寻找 -

handle_global_suman node_exec_args "$@" --suman-shell

问题是它与and一起handle_global_suman工作,如果我进入,那么我必须更改其他代码,并且宁愿避免这种情况。$1$2--suman-shell$3

初步回答:

    local args=("$@")
    args+=("--suman-shell")

    if [ -z "$LOCAL_SUMAN" ]; then
        echo " => No local Suman executable could be found, given the present working directory => $PWD"
        echo " => Warning...attempting to run a globally installed version of Suman..."
        local -a node_exec_args=( )
        handle_global_suman node_exec_args "${args[@]}"
    else
        NODE_PATH="${NEW_NODE_PATH}" PATH="${NEW_PATH}" node "$LOCAL_SUMAN" "${args[@]}";
    fi

答案1

将参数放入数组中,然后追加到数组中。

args=("$@")
args+=(foo)
args+=(bar)
baz "${args[@]}"

答案2

无需求助于数组 - 您可以使用以下方法自行操作参数set --

$ manipulateArgs() {
  set -- 'my prefix' "$@" 'my suffix'
  for i in "$@"; do echo "$i"; done
}

$ manipulateArgs 'the middle'
my prefix
the middle
my suffix

答案3

handle_global_suman node_exec_args --suman-shell "$@"

相关内容