Created
June 26, 2012 20:30
-
-
Save kristopherjohnson/2998722 to your computer and use it in GitHub Desktop.
Bash snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## Debugging: Show expanded commands before executing them | |
set -x | |
## Debugging: Exit with error on attempt to use unset variable | |
set -u | |
## Run commands in subshell | |
( /bin/foo; /bin/bar ) | |
## Check command result | |
/bin/foo bar baz | |
if [ $? -ne 0 ]; then # Note: Don't leave out the spaces: they are significant | |
echo "foo returned result $?" | |
exit 1 | |
else | |
echo "foo was cool" | |
fi | |
## Or, more compactly | |
if ! /bin/foo bar baz; then echo "foo returned $?"; exit 1; fi | |
## Set environment variable if not already set | |
if [ -z "$MYVAR" ]; then export MYVAR="fiddledy dee"; fi | |
## Create directory if it does not exist | |
if [ ! -d "$MYDIR" ]; then /bin/mkdir -p "$MYDIR"; fi | |
## Send output to stdout and to log file | |
/bin/foo 2>&1 | tee foo.log | |
## Do something for each file in a directory | |
for f in $( ls ); do echo $f; done | |
## Function | |
foo () | |
{ | |
echo "foo was called with arguments: $1 $2" | |
} | |
foo hello world | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used in this blog entry: http://undefinedvalue.com/2012/06/23/bash-scripting-cheatsheet