Shell-Scripting Cheat Sheet

See Also: Bash sed awk

Date Handling

Convert Date To Unix Timestamp

date -d "$date" +%s
Note that this only works for American style dates. European "25.06.2014" like dates are not supported. The simple solution is to convert them first to "2014-06-25" for example with
sed 's/\([0-9]*\)\.\([0-9]*\)\.([0-9]*\)/\3-\2-\1/'

Convert From Unix Timestamp

date -d "1970-01-01 1234567890 sec GMT"

Calculate Last Day of Month

Found here:
cal $(date "+%M %y") | grep -v ^$ | tail -1 | sed 's/^.* \([0-9]*\)$/\1/'

Lock Files

Using "flock":
flock /tmp/myapp.lock <some command>
flock -w 10 /tmp/myapp.lock <some command>
Using "lockfile-*" commands:
lockfile-create /tmp/myapp.lock
lockfile-touch  /tmp/myapp.lock
lockfile-remove /tmp/myapp.lock

shflags - portable getops

If you ever need to port between different Unix derivates use shflags a Google library providing standard parameter handling. Example:
source shflags

DEFINE_string 'value' '0' 'an example value to pass with default value "0"' 'v'

FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

echo "${FLAGS_value}!"

Other Topics