Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

What I am trying to do in bash is write a script, foo, that when I run $(foo), it changes the directory and runs a script using source. The contents of foo:

echo cd bar
echo "&&"
echo source baz

When I run $(foo), it changes directory to "bar", but it does not run source baz. Is there any way to accomplish this?

share|improve this question
Plus, why would you want to do that? This seems a little contrived and I'm sure there are better ways to achieve what you need. – slhck Feb 6 '13 at 21:42
@slhck I can't affect the shell from inside a script or program. The only ways to affect the shell are with command substitution or source, so I'm trying to find a way to do that. – Kevin Marsolais Feb 6 '13 at 22:13
Why are you storing the commands to execute in a variable in the first place? – chepner Feb 8 '13 at 13:53
up vote 1 down vote accepted

You need to eval the output:

eval $(foo)

Otherwise, &&(or any other similar language element) is treated as if it were wrapped in quotation marks: a regular argument to cd.

$ echo $(foo)
cd bar && source baz

Skipping the leading echo, this would execute cd with the four arguments bar && source baz, silently dropping all but the first.

share|improve this answer
Note that, depending on your application, this might not be a really good idea. – Daniel Beck Feb 6 '13 at 22:27
Seems to work, if not the most elegant solution. Thanks. – Kevin Marsolais Feb 6 '13 at 22:48

You can use aliases (see also: man bash) to do what your trying to do.

alias foo='cd bar && source baz'

will change directory to bar and source baz when you execute foo.

share|improve this answer

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.