0

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

1

2 Answers 2

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)"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.