| Useful bash command |
| Software |
| Friday, 24 February 2012 13:29 |
|
Here's a super helpful little bash snippet I use a lot. It adds very basic error handling to bash commands.
function cmd {
cmd=$*
echo $cmd
eval $cmd
if [[ "$?" != "0" ]]; then
echo "The last command failed. Setup will now exit.";
exit 1;
fi
}
So, instead of writing code like this...
echo 'scp example.com:/foo/bar.txt /foo/bar.txt'
scp example.com:/foo/bar.txt /foo/bar.txt
if [[ "$?" != "0" ]]; then
echo "The last command failed. Exiting.";
exit 1;
fi
echo 'echo "more stuff" >> /foo/bar.txt'
echo "more stuff" >> /foo/bar.txt
if [[ "$?" != "0" ]]; then
echo "The last command failed. Exiting.";
exit 1;
fi
echo 'cp /foo/bar.txt /baz/bar.txt'
cp /foo/bar.txt /baz/bar.txt
if [[ "$?" != "0" ]]; then
echo "The last command failed. Exiting.";
exit 1;
fi
You can just write this...
cmd scp example.com:/foo/bar.txt /foo/bar.txt
cmd 'echo "more stuff" >> /foo/bar.txt'
cmd cp /foo/bar.txt /baz/bar.txt
Note that if you want to have pipes and redirects in your command, you must use quotes to pass the entire command as a single parameter, like this: cmd "cat /etc/bash.bashrc | grep -v APPLICATION_ENV > /tmp/bash.bashrc" Of course you may want to tweak it and there are many cases when you need more advanced error handling. But this works in many cases and makes it much faster to write up a shell script that needs to stop if a command fails. |