Reputation: 4328
Let's say I have the following snippet of code, which at runtime generates a string which I want executed in the shell (just like if I'd just pasted the string into a terminal and hit enter":
cmd=""
for i in first second third
do
cmd="$cmd | grep $i"
done
cmd="cat /usr/share/dict/words $cmd"
$cmd
The problem here is that the pipe characters are not interpreted as such, however; they're treated as parameters to cat
, as though I had escaped them:
cat: |: No such file or directory
cat: grep: No such file or directory
cat: first: No such file or directory
cat: |: No such file or directory
cat: grep: No such file or directory
cat: second: No such file or directory
cat: |: No such file or directory
cat: grep: No such file or directory
cat: third: No such file or directory
Is there a way to "execute" the string with the pipe characters unescaped? Is there a better way to generate code like this at runtime?
I'd prefer a portable solution but bashisms are acceptable.
Upvotes: 2
Views: 291