Bash
將參數附加到參數列表
我有以下 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
問題是它
handle_global_suman
適用於$1
and$2
如果我 make--suman-shell
into$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
將參數放入數組中,然後追加到數組中。
args=("$@") args+=(foo) args+=(bar) baz "${args[@]}"
無需求助於數組 - 您可以使用以下方法自行操作參數
set --
:$ manipulateArgs() { set -- 'my prefix' "$@" 'my suffix' for i in "$@"; do echo "$i"; done } $ manipulateArgs 'the middle' my prefix the middle my suffix