Two bash quirks

TIL bash is a bit tricky to get right:

    1. When you chain multiple processes via pipes under bash , the exit code available in $? is actually the return code of the last process in the chain. This turns out to be very relevant if you pipe the output to something like the tee utility which almost always will return successfully. In order to catch the return code use set -o pipefail  before you execute the command.
    2. Let’s say you want to wrap a command in a bash script and that command takes a bunch of parameters. A quick and dirty way would be to call the command like this from your bash script $COMMAND $*. This would pass to the command all the arguments supplied to the script. In most cases this ok but if one of the arguments contains a space, bash will split it and serve it as two separate arguments to your command. So instead of $COMMAND  -argument "First Second"  bash will send this as $COMMAND -argument "First" "Second" . The workaround is to use $@ and wrap that in quotes. So : $COMMAND "$@"


Leave a Reply

Your email address will not be published. Required fields are marked *