Joe
Joe

Reputation: 720

Passing a 'command with a pipe' as a bash function parameter

I've written a tiny bash function which simply runs a command if $current_user_input = yes

function if_yes_run_with {
    if [ $current_user_input = yes ]
    then
        $1
    fi
}

I call it a number of times perfectly fine e.g:

if_yes_run_with 'brew update'

however, I've reached a point where I'd like to pass a command to it that includes a pipe:

if_yes_run_with '\curl -L https://get.rvm.io | bash -s stable'

the function appears to only evaluate command up to the pipe. The outcome of running it therefore gives the same result as:

if_yes_run_with \curl -L https://get.rvm.io

Can anyone help with passing a 'command with a pipe' as a parameter to a bash function?

Upvotes: 6

Views: 2071

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

It's difficult to do what you want in a safe and robust way. Greg's Bash Wiki says it best:

Variables hold data. Functions hold code. Don't put code inside variables!

I wouldn't have it execute the command directly. Instead, have the function return success/failure. Then you can do whatever you like at the calling end with && or if.

is_user_input_enabled() {
    [[ $current_user_input = yes ]]
}

is_user_input_enabled && brew update
is_user_input_enabled && curl -L https://get.rvm.io | bash -s stable

Notice how you don't need any extra quotes or escaping to make this work.

See also:

Upvotes: 4

Related Questions