Bash – Append Argument to Arguments List

argumentsbashshellshell-script

I have the following Bash code:

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
}

when the suman command is executed by the user with no arguments, then this is hit:

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

my question is – how can I append an argument to the "$@" value?
I need to simply do something like:

handle_global_suman node_exec_args "--suman-shell $@"

obviously that's wrong but I cannot figure out how to do it. What I am not looking for –

handle_global_suman node_exec_args "$@" --suman-shell

the problem is that handle_global_suman works with $1 and $2 and if I make --suman-shell into $3, then I have to change other code, and would rather avoid that.

Preliminary answer:

    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

Best Answer

Put the arguments into an array and then append to the array.

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