Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This works—

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

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
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.


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

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


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

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

share|improve this answer
When such an alias is run non-interactively, i.e. in a script, you need shopt -s expand_aliases before the first use of the alias - interestingly not necessarily before the alias definition. – valid Mar 20 '15 at 14:06

Your Answer


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.