Reputation:
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 linux :/
I've searched a lot but been unable to find a satisfying answer.
thank you very much for any tips !
Upvotes: 0
Views: 2725
Reputation:
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 !
Upvotes: 0
Reputation: 25599
Don't put the command into a variable! Just execute it! What's wrong with :
#!/bin/bash
launchctl list | grep -i \"twshows\"
Upvotes: 1
Reputation: 140367
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
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.
Upvotes: 2