开发者

Mac OS Shell exec command with a pipe in it

It might be a really dummy question but I'm banging my head against the wall here...

Why does this code :

#!/bin/bash -x    
cmd="launchctl list | grep -i \"twshows\""
echo $($cmd)

Produce this output :

% ./test.sh
+ cmd='launchctl list | grep -i "twshows"'
++ launchctl list '|' grep -i '"twshows"'
usage: launchctl list [-x] [label]
+ echo

Instead of simply executing the command. What is wrong with this pipe ? Is not well escaped ? I'm really desperate here, never encounter such thing on l开发者_StackOverflow社区inux :/

I've searched a lot but been unable to find a satisfying answer.

thank you very much for any tips !


What you want is to do is use eval to evaluate the $cmd variable:

#!/bin/bash -x    
cmd="launchctl list | grep -i \"twshows\""
eval $cmd

Big Scary Warning

eval can be quite evil because it will evaluate whatever is in that variable. If that variable is initialized from user-supplied input, say rm -rf \; echo 'gotcha!' it will execute that with the same privileges as the shell you are running it under.


Don't put the command into a variable! Just execute it! What's wrong with :

#!/bin/bash
launchctl list | grep -i \"twshows\"


Okey so I'm answering myself... I found out that when doing ths :

echo $(launchctl list | grep -i "aqua")

It works.

The main difference being the escaping technique. If you escape the whole command, like so :

echo $(" launchctl list | grep -i "aqua" ")

The command will not be found. If you put the command in a variable, the same will happend. And finally, if you escape the double quotes for grep, it will not works either.

So the only solution is to NOT escape the command, seems strange to me but at leat.. it works !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜