简体   繁体   English

传递'带管道的命令'作为bash函数参数

[英]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 我编写了一个小的bash函数,如果$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 eg: 我称它为好几次,例如:

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? 任何人都可以帮助将带有管道的'命令'作为参数传递给bash函数吗?

It's difficult to do what you want in a safe and robust way. 以安全可靠的方式做你想做的事很难。 Greg's Bash Wiki says it best: 格雷格的Bash Wiki说得最好:

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 . 然后,您可以使用&&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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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