B T
B T

Reputation: 60975

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?

Upvotes: 8

Views: 3143

Answers (3)

Alexander Mills
Alexander Mills

Reputation: 100270

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

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247082

@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 "$@"

Upvotes: 20

that other guy
that other guy

Reputation: 123610

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 "$@"

Upvotes: 5

Related Questions