Don't get caught by -c

Posted by Andrew Sat, 02 Jul 2011 23:37:45 GMT

Say you want to set an environment variable and then run a command. You could do something like

FOO=bar /usr/bin/env

You'd see FOO=bar in the output. If you're using something like capistrano you'll run this command remotely with a wrapper of /bin/bash -c your command

Can you spot what's wrong with this command?

bash -c FOO=bar /usr/bin/env

What do you expect it to output? Same as above? Well it outputs nothing and returns immediately with a 0 (success) exit code. Ok, so what if you wrapped it in quotes, that won't change anything, will it?

bash -c 'FOO=bar /usr/bin/env'

Nope, it runs properly now as at the beginning. Ok, what if you prepend it with another command. 

bash -c ls && FOO=bar /usr/bin/env

Now they both run. I am still trying to figure this out but it looks like this has to do with how assignments are treated.


Use the following link to trackback from your own site:

    Comments are disabled