Bash:使用带有管道的函数作为另一个函数的参数

时间:2016-10-12 11:24:07

标签: bash macos unix

我正在尝试为其他函数创建函数包装器以区分它的终端

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)"

function wrapper {
    echo $red_line;
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)";
    $2;
    echo $red_line;
}

function foo {
    wrapper "custom command description" "ps axo pid,stat,pcpu,comm | tail -n 10;"
}

但发生了错误:ps: illegal argument: |

我尝试使用$(ps ... | tail -n 10)和反引号代替字符串,然后使用echo $2将结果打印在包装中,但发现了其他错误

还尝试了"eval $(ps ... | tail -n 10)",但它也无效。

一切正常,没有包装:

function pss {
    echo $red_line
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)formatted 'ps ax' command $(tput sgr 0)"

    ps axo pid,stat,pcpu,comm | tail -n $1;

    echo $red_line
}

result screenshot

2 个答案:

答案 0 :(得分:1)

Tnx @chepner用于引用关于将复杂命令作为参数传递的帖子。 但实际问题是在echowrapper中的函数参数中混淆了双引号。

正确的代码:

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)"

function wrapper {
    echo $red_line;
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)";
    echo "$2";
    echo $red_line;
}

function pss {
    res="$(ps axo pid,stat,pcpu,comm | tail -n $1)"
    wrapper "custom command description" "$res"
    # also work: 
    # wrapper "custom command description" "$(ps axo pid,stat,pcpu,comm | tail -n $1)"
}

答案 1 :(得分:1)

Aiven Lebowski的回答是正确的。但如果你真的想保持foo原样并在你放置它的地方执行2美元,你只需要做eval

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)"

function wrapper {
    echo $red_line;
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)";
    eval $2
    echo $red_line;
}

function foo {
    wrapper "custom command description" "ps axo pid,stat,pcpu,comm | tail -n 10;"
}

我希望这会有所帮助