Linux - Run shell script function argument as a command inside the function

My intention is to create a Linux shell script function which perform some generic calls when the command is passed into as function argument. For example


As you can see, the run() to will execute its input argument as a command and generically pipe to some log file.

The run() work fine most of the time until the command become complex, for example, piping the output (e.g. fgrep -w processor /proc/cpuinfo | wc -l).

If I run the above program, the output has some error


When I turn on shell debugging (set -x), it shows that the | is single quoted. That cause the command to treat | as literal string, and thus, the error on the fgrep call.


To workaround it, in the run(), you need to add ksh -c and double quote $@.  The fix explicitly call ksh -c and treat everything inside "$@" as literal command string. The double quote is important here. With the double quote, ksh will not escape the | character.


and it gives the proper output.



Comments

Popular Posts