简体   繁体   中英

Prepend to command line arguments in linux/bash

I want to pass along the command line arguments given to script to another command, but I also want to add some additional arguments on the front first. How can I do this with bash?

This will send all the arguments through to the command:

command $@

But I want something more like:

command [argument1, argument2, $@]

How can you do something like this in bash?

@ThatOtherGuy's answer is correct.

If you were looking to "unshift" a couple of arguments into the positional parameters, do this:

set -- arg1 arg2 "$@"
cmd "$@"

If you have grep foo and you want to add -f before foo , you can use grep -f foo . The same thing applies here:

cmd argument1 argument2 "$@"

If you want a more generic way to do this (recommended), use this:

#!/usr/bin/env bash

function xyz {
  echo "${args[@]}"  # arguments will printed out
}

function abc {
    local args=()
    args+=(argument1)
    args+=(argument2)
    args+=("$@")
    xyz "${args[@]}"
}

to test, source the above code

source script.sh && abc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM