#!/bin/bashTo produce some interesting debugging output information,
#!/bin/bash -xSet the passed arguments to an array, e.g.
$ foo.sh bar
args = ("$@") # args = barUse
"$#"
to get the number of arguments, e.g.
if [ "$#" -ne 1 ]; then echo "Must have exactly one argument." exit 1 fiFind out if a file exists
if [ -f "foo.txt" ]; then cat foo.txt fi # Check if file does not exist if [ ! -f "foo.txt" ]; then echo "foo.txt not found!" fiTo get the return code from previous command, use
$?
somecommand if [ $? -eq 0 ] then echo "command ran successfully." else echo "somecommand failed." >&2 exit 1 fi
somecommand if [ $? -ne 0 ]; then # output to stderr echo "[`date`] [error]somecommand failed." >&2 exit 1 fi # output to stdout echo "[`date`] [notice]somecommand succeeded."To add timestamp to a command's output:
$ somecommand | sed "s/^/[`date`] /" # Timestamp the error message, too $ somecommand 2>&1 | sed "s/^/[`date`] /"To check to see if an environment variable is set, use
-z
to check for zero-length string:
if [ -z "$TEST_VAR" ] then export $TEST_VAR="some value" fiTo unset an environment variable:
$ unset TEST_VAR
To print a newline with
echo
, use these option:
(Note: Linux/Unix does not interpret carriage return char: \r
)
-n do not output the trailing newline -e enable interpretation of backslash escapese.g.
$ echo -e "Hello\nWorld " Hello World $ echo -ne "Hello\nWorld " Hello World $To get the script's base name and directory:
SCRIPTNAME=`basename $0` SCRIPTDIR=`dirname $0`