2

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.

1
  • 2
    If you can keep from getting too trusting, look at eval, i.e. eval $cmd. Constructing command lines programmatically is begging to get pwnt. Ask around about Little Bobby Tables. Commented Apr 16, 2014 at 0:16

1 Answer 1

4

To execute the string you can use eval $cmd

Sign up to request clarification or add additional context in comments.

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.