Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created June 26, 2012 20:30
Show Gist options
  • Save kristopherjohnson/2998722 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/2998722 to your computer and use it in GitHub Desktop.
Bash snippets
#!/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
@kristopherjohnson
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment