Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This works—

$ x='grep a'
$ echo ab | $x
ab

This doesn't—

$ x='grep a | grep b'
$ echo ab | $x
grep: |: No such file or directory
grep: grep: No such file or directory
grep: b: No such file or directory

It appears in the latter case, grep a | grep b is seen as a single command, i.e. grep a \| grep b.

How do I get the second example to work without modifying x?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

When you want to run variables that contain code you'll often want to use the command eval. This will expand the contents of the variable so that they can be executed.

Example

$ x='grep a | grep b'
$  echo ab | eval $x
ab

Using eval is often discourage though, so use caution, see this BashFAQ titled: Eval command and security issues for more examples!

References

share|improve this answer

Ah, I figured it out after some experimentation—use alias

$ x='grep a | grep b'
$ alias y=$x
$ echo ab | y
ab

Please do post any other ways to do this—I'd be interested in alternatives.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.