HOWTO: Insert date automatically with sh

From SHellium Wiki
Jump to: navigation, search
Geographylogo.png In other languages: English | Afrikaans | Albanian | Arabic | Brazilian | Bulgarian | Catalan | Chinese | Croatian | Czech | Danish | Dutch | Esperanto | Estonian | Filipino | Finnish | Flemish | French | German | Greek | Hebrew | Hindi | Hungarian | Indonesian | Italian | Japanese | Latvian | Lithuanian | Macedonian | Malay | Malayalam | Norwegian (Bokmål) | Norwegian (Nynorsk) | Persian | Polish | Portuguese | Romanian | Russian | Serbian | Slovak | Slovenian | Spanish | Swedish | Turkish | Ukrainian | Urdu

You can insert the current date anywhere inside the shell, or a shell script using linux's date command with formatting.

date +%d%b%y       Example: 30Sep08
date +F                   : 2008-09-30
date '+%B %e, %Y'         : September 30, 2008

Date can be used for time as well.

date +%T       Example : 12:57:06
date +%I:%M            : 12:57

Include this inside your shell commands or shell scripts by using $(date <formatting>)
Here is an example script to backup a directory using the date to identify when the backup was done.

#!/bin/sh
# File: backupsrc.sh
#
# Places a .tar.bz2 of src directory into ~/backups

# Create directory ~/backups only if it doesn't already exist
if [ ! -d ~/backups] ; then
  mkdir ~/backups]
fi
# Make sure mkdir was successful
if [ ! -d ~/backups] ; then
  cat << EOF
Can't create ~/backups, check permissions.
EOF
fi
echo Backing up src directory to ~/backups...
echo "tar -jcf srcbackup.$(date '+%d%b%y').tar.bz2 src" | sh
mv srcbackup.$(date '+%d%b%y').tar.bz2 ~/backups
echo "ls -Fsh ~/backups/srcbackup.$(date '+%d%b%y').tar.bz2/ | sh
echo Done.
Personal tools
Namespaces

Variants
Actions
Navigation
Indexes
SHellium Sites
Toolbox