How to pass all arguments of a function along to another command?

Hello I have this in my ~/.bash_profile

export GOPATH="$HOME/go_projects"
export GOBIN="$GOPATH/bin"

program(){
        $GOBIN/program $1
}

so I’m able to do program "-p hello_world -tSu". Is there any way to run the program and custom flags without using the quotation marks? if I do just program -p hello_world -tSu it’ll only use the -p flag and everything after the space will be ignored.

Asked By: nooby

||

Within your program shell function, use "$@" to refer to the list of all command line arguments given to the function. With the quotes, each command line argument given to program would additionally be individually quoted (you generally want this).

program () {
    "$GOBIN"/program "$@"
}

You would then call program like so:

program -p hello_world -tSu

or, if you want to pass hello world instead of hello_world,

program -p 'hello world' -tSu

Using $1 refers to only the first command line argument (and $2 would refer to the second, etc.), as you have noticed. The value of $1 would additionally be split on white-spaces and each generated string would undergo filename globbing, since the expansion is unquoted. This would make it impossible to correctly pass an argument that contains spaces or filename globbing patterns to the function.

Answered By: Kusalananda

"$@" is the way to provide pass all arguments received by a function / script, as answered by Kusalananda.

However, given that you seem to be using a folder with your go programs, I think you would be better served by simply adding your $GOBIN folder to your PATH:

export GOPATH="$HOME/go_projects"
export GOBIN="$GOPATH/bin"
export PATH="$PATH:$GOBIN"

This way you could run any program stored in $GOBIN just by typing its name (unless it has the same name of an existing program, we are appending $GOBIN to $PATH, so these programs would be picked last).

PS: For completeness, there is a third option which would be to use an alias instead of a function, you could place in .bashrc:

alias program="$GOBIN/program"
Answered By: Ángel

What worked for me is the following:

m() {
    args="$@"
    usql mysql://root@localhost:3306 -c $args
}

This actually placed a quoted set of arguments at the end of my command, such that I can run commands like:

m show databases;

And it actually runs

usql mysql://root@localhost:3306 -c "show databases;"
Answered By: Kyle Aoki
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.