Wednesday, August 24, 2011

devil is in the details.. #!/bin/bash

What's wrong with this:
su user -c "bash -xe" << 'EOF'
   my script
Sometimes writing constructs you have not used million times can cost precious time, in case you are *not* absolutely sure about all implications.

There is really nothing wrong with the above code if "my script" is very short and you understand deeply what it does. But if not, you may end up with your script terminating in the middle and ext code being 0 which is something I didn't expect from a script run with `-xe` options.

In my case I had a long script that just ended in the middle on an apache-ant invocation and script result was successful in our CI system. The problem is actually that apache-ant for some reason sucked everything on its stdin which in this case happened to be the rest of my script. Bash it seems, does not read the whole input so commands and programs called from within the script can eat parts of your script.

I've no idea why the particular apache-ant build never asks questions and completes happily with < /dev/null and still it eats the stdin. Maybe that's why it took me so much time to see the cause. I hope this is the reason it took me so much time to see the cause!

Conclusion is: use what you're absolutely confident in, alternatively plan some time in ahead for debugging:
cat > << 'EOF'
   my script
su user -- -xe
P.S. "bash -c"  is also solid for one liners