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

I have a bash script that should be executing a number of commands. The commands work fine when entered in a termainal but when I try to execute them from inside the script they don't work, so I assume it's something environment-specific.

In the script I have

exec "$cmd"

and it doesn't work, while if I copy the contents of $cmd and paste in a terminal it works fine.

How do I keep the current environment when running the script? Or do you have any other idea what it might be?

share|improve this question
Running the script does not change the environment by default. You've misdiagnosed the problem. – Ignacio Vazquez-Abrams Aug 22 '12 at 11:29
Be sure to export the variables needed by the script before running it. – choroba Aug 22 '12 at 11:31
Ingacio: Hmkay, then I don't know. I do exec "$command" in the script and it doesn't work, the exact same command in the terminal work. choroba: I'm not sure which variables it is :/ it's a big enterprise environment with scripts and variables all over the place. – dutt Aug 22 '12 at 11:36
Is there some special reason you are using exec? Why not just write the command directly? e.g.: `cmd=ls; $cmd;' – terdon Aug 22 '12 at 12:56
I tried both and neither worked, is there any difference? – dutt Aug 22 '12 at 13:41

Put the command in an array instead.

arr=(foo bar baz quux)
exec "${arr[@]}"
share|improve this answer

Type set -o allexport at the top of your bash script. This should automatically export all variables you define. (Do note that this is considered bad style; a better thing would be to just export the proper variables).

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.