TAGS :Viewed: 8 - Published at: a few seconds ago

[ Bash: using function with pipe as argument for another function ]

I'm trying to make function-wrapper for another functions to distinguish its in terminal

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;"
}

but error was occurred: ps: illegal argument: |

I've tried to use $(ps ... | tail -n 10) and backticks instead of string and then print out result in wrapper with echo $2, but caught another errors

Also tried "eval $(ps ... | tail -n 10)" and it also didn't work.

Everything works just fine w/o wrapper:

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

Answer 1


Tnx @chepner for referring post about passing complex commands as argument. But the actual problem was with mess with double quotes in functions arguments in echo and wrapper.

Correct code:

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)"
}

Answer 2


Aiven Lebowski 's answer is correct. but if you really wanted to keep foo as-is and execute $2 in place where you put it, you only needed to do 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;"
}

I hope this helps