Cheatsheet: dynamic date value in shell scripts

using a variable – easier to read in scripts:
NOW=$(date +"%Y%m%d%H%M%S")
echo "bar" > "$NOW"foobar.txt

one-line, equivalent to above:
echo "bar" > $(date +"%Y%m%d%H%M%S")foobar.txt

alternate single-line format:
echo "bar" >> $(date "+myfile%Y%m%d.txt")

man strftime to see formatting values

Use sudo with echo in shell

You can’t use sudo directly with echo in shell scripts / command line, so you need to use tee with append (-a). For example (simplified script example to update /etc/hosts for localhost entries):

if [ $(cat /etc/hosts | egrep -c "\s$1") == 0 ]; then
	echo "127.0.0.1 $1" | sudo tee -a /etc/hosts
fi

crontab example line with shell export and output to logfile

(export PATH=$PATH:/usr/local/bin; \
     /path/to/myscript.sh) >> /home/www/log/publish.log 2>&1

date format for linux shell scripts

#echo "starting script at" $(date +"%Y-%m-%d %H:%M:%S") "..."

starting publish script at 2012-10-01 15:52:14 …

see: linux-unix-formatting-dates-for-display