Hide

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again.

Delete that bloated snippets file you've been using and share your personal repository with the world. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.


If you have a new feature suggestion or find a bug, please get in touch via http://commandlinefu.uservoice.com/

Get involved!

You can sign-in using OpenID credentials, or register a traditional username and password.

First-time OpenID users will be automatically assigned a username which can be changed after signing in.

Hide

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for:

Hide

News

2011-03-12 - Confoo 2011 presentation
Slides are available from the commandlinefu presentation at Confoo 2011: http://presentations.codeinthehole.com/confoo2011/
2011-01-04 - Moderation now required for new commands
To try and put and end to the spamming, new commands require moderation before they will appear on the site.
2010-12-27 - Apologies for not banning the trolls sooner
Have been away from the interwebs over Christmas. Will be more vigilant henceforth.
2010-09-24 - OAuth and pagination problems fixed
Apologies for the delay in getting Twitter's OAuth supported. Annoying pagination gremlin also fixed.
Hide

Tags

Hide

Functions

Commands using date from sorted by
Terminal - Commands using date - 146 results
firefox http://en.wikipedia.org/wiki/$(date +'%b_%d')
tar jcpf /home/[usuario]/etc-$(hostname)-backup-$(date +%Y%m%d-%H%M%S).tar.bz2 /etc
2011-04-29 22:53:11
User: mack
Functions: date tar
-1

Simple Compressed Backup of the /etc

Linux compatible

date +%Y%m%d%T -s "`ssh user@server 'date "+%Y%m%d %T"'`"
2011-01-11 10:33:32
Functions: date
Tags: ssh ,NTP ,Date
0

If you are stuck behind a firewall and want to synchronize time with another server but you do not want to port forward NTP (which uses UDP) then this command is handy. It gets the time from a server and sets the local time. It is not that accurate but I can live with a second or so drift.

buf() { cp -v $1 ${1/${1%%.*}/$f-$(date +"%Y%m%d_%H%M%S")};}
buf() { f=${1%%.*};e=${1/$f/};cp -v $1 $f-$(date +"%Y%m%d_%H%M%S")$e;}
2010-12-15 09:50:04
User: unefunge
Functions: cp date
0

"infix" version in bash (4.x+)

Remove -v to make it silent.

BTW: The OP forgot to use "cat" and "nmap" ;-) I had a good laugh though.

qrurl() { curl "http://chart.apis.google.com/chart?chs=150x150&cht=qr&chld=H%7C0&chl=$1" -o qr.$(date +%Y%m%d%H%M%S).png; }
2010-12-15 04:40:22
User: bartonski
Functions: date
7

QR codes are those funny square 2d bar codes that everyone seems to be pointing their smart phones at.

Try the following...

qrurl http://xkcd.com

Then open qr.*.png in your favorite image viewer.

Point your the bar code reader on your smart phone at the code, and you'll shortly be reading xkcd on your phone.

URLs are not the only thing that can be encoded by QR codes... short texts (to around 2K) can be encoded this way, although this function doesn't do any URL encoding, so unless you want to do that by hand it won't be useful for that.

buf () {oldname=$1; if [ "$oldname" != "" ]; then datepart=$(date +%Y-%m-%d); firstpart=`echo $oldname | cut -d "." -f 1`; newname=`echo $oldname | sed s/$firstpart/$firstpart.$datepart/`; cp -i ${oldname} ${newname}; fi }
2010-12-14 19:58:34
User: Seebi
Functions: cp cut date sed
-3

This backup function preserve the file suffix allowing zsh suffix aliases and desktop default actions to work with the backup file too.

buf () { cp $1{,$(date +%Y%m%d_%H%M%S)}; }
2010-12-14 14:02:03
User: unefunge
Functions: cp date
2

1. you don't need to prepend the year with 20 - just use Y instead of y

2. you may want to make your function a bit more secure:

buf () { cp ${1?filename not specified}{,$(date +%Y%m%d_%H%M%S)}; }

buf () { filename=$1; filetime=$(date +%Y%m%d_%H%M%S); cp ${filename} ${filename}_${filetime}; }
2010-12-14 13:19:52
User: dopeman
Functions: cp date
1
buf myfile.txt

This is useful when you are making small but frequent changes to a file. It keeps things organised and clear for another administrator to see what changed and at what time. An overview of changes can be deduced using a simple:

ls -ltr
read -a A <<<"8 9 5 10 6 0 3 11 7 4";B='.*.**..*....***';for C in $(date +"%H%M"|fold -w1);do echo "${B:${A[C]}:4}";done
for a in $(date +"%H%M"|cut -b1,2,3,4 --output-delimiter=" ");do case "$a" in 0)echo "....";;1)echo "...*";;2)echo "..*.";;3)echo "..**";;4)echo ".*..";;5)echo ".*.*";;6)echo ".**.";;7)echo ".***";;8)echo "*...";;9)echo "*..*";;esac;done
tail -f file | while read line; do echo -n $(date -u -Ins); echo -e "\t$line"; done
2010-11-19 10:01:57
User: hfs
Functions: date echo file read tail
Tags: tail date
5

This is useful when watching a log file that does not contain timestamps itself.

If the file already has content when starting the command, the first lines will have the "wrong" timestamp when the command was started and not when the lines were originally written.

alias tarred='( ( D=`builtin pwd`; F=$(date +$HOME/`sed "s,[/ ],#,g" <<< ${D/${HOME}/}`#-%F.tgz); tar --ignore-failed-read --transform "s,^${D%/*},`date +${D%/*}.%F`,S" -czPf "$F" "$D" &>/dev/null ) & )'
2010-11-18 06:24:34
User: AskApache
Functions: alias date tar
7

This is freaking sweet!!! Here is the full alias, (I didn't want to cause display problems on commandlinefu.com's homepage):

alias tarred='( ( D=`builtin pwd`; F=$(date +$HOME/`sed "s,[/ ],#,g" <<< ${D/${HOME}/}`#-%F.tgz); S=$SECONDS; tar --ignore-failed-read --transform "s,^${D%/*},`date +${D%/*}.%F`,S" -czPf "$"F "$D" && logger -s "Tarred $D to $F in $(($SECONDS-$S)) seconds" ) & )'

Creates a .tgz archive of whatever directory it is run from, in the background, detached from current shell so if you logout it will still complete. Also, you can run this as many times as you want, if the archive .tgz already exists, it just moves it to a numbered backup '--backup=numbered'. The coolest part of this is the transformation performed by tar and sed so that the archive file names are automatically created, and when you extract the archive file it is completely safe thanks to the transform command.

If you archive lets say /home/tombdigger/new-stuff-to-backup/ it will create the archive /home/#home#tombdigger#new-stuff-to-backup#-2010-11-18.tgz Then when you extract it, like tar -xvzf #home#tombdigger#new-stuff-to-backup#-2010-11-18.tgz instead of overwriting an existing /home/tombdigger/new-stuff-to-backup/ directory, it will extract to /home/tombdigger/new-stuff-to-backup.2010-11-18/

Basically, the tar archive filename is the PWD with all '/' replaced with '#', and the date is appended to the name so that multiple archives are easily managed. This example saves all archives to your $HOME/archive-name.tgz, but I have a $BKDIR variable with my backup location for each shell user, so I just replaced HOME with BKDIR in the alias.

So when I ran this in /opt/askapache/SOURCE/lockfile-progs-0.1.11/ the archive was created at /askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz

Upon completion, uses the universal logger tool to output its completion to syslog and stderr (printed to your terminal), just remove that part if you don't want it, or just remove the '-s ' option from logger to keep the logs only in syslog and not on your terminal.

Here's how my syslog server recorded this..

2010-11-18T00:44:13-05:00 gravedigger.askapache.com (127.0.0.5) [user] [notice] (logger:) Tarred /opt/askapache/SOURCE/lockfile-progs-0.1.11 to /askapache-bk/tarred/#opt#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz in 4 seconds

Caveats

Really this is very robust and foolproof, the only issues I ever have with it (I've been using this for years on my web servers) is if you run it in a directory and then a file changes in that directory, you get a warning message and your archive might have a problem for the changed file. This happens when running this in a logs directory, a temp dir, etc.. That's the only issue I've ever had, really nothing more than a heads up.

Advanced:

This is a simple alias, and very useful as it works on basically every linux box with semi-current tar and GNU coreutils, bash, and sed.. But if you want to customize it or pass parameters (like a dir to backup instead of pwd), check out this function I use.. this is what I created the alias from BTW, replacing my aa_status function with logger, and adding $SECONDS runtime instead of using tar's --totals

function tarred ()

{

local GZIP='--fast' PWD=${1:-`pwd`} F=$(date +${BKDIR}/%m-%d-%g-%H%M-`sed -u 's/[\/\ ]/#/g'

[[ ! -r "$PWD" ]] && echo "Bad permissions for $PWD" 1>&2 && return 2;

( ( tar --totals --ignore-failed-read --transform "s@^${PWD%/*}@`date +${PWD%/*}.%m-%d-%g`@S" -czPf $F $PWD && aa_status "Completed Tarp of $PWD to $F" ) & )

}

#From my .bash_profile http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

tar cfz backup-$(date --iso).tar.gz somedirs
date +"%V"
2010-11-17 14:59:31
User: SuperFly
Functions: date
4

Not as cool as the python example, but it still works.

wget -O xkcd_$(date +%y-%m-%d).png `lynx --dump http://xkcd.com/|grep png`; eog xkcd_$(date +%y-%m-%d).png
TZ="$tz_dest" date -d "$(TZ="$tz_orig" date -d "$tm")"
date | md5sum
date --date=yesterday +%Y%m%d
2010-09-08 12:29:31
User: vinayv
Functions: date
Tags: bash date
2

The "date' command has options to easily format the date, day, month, time, etc. But what if you want a relative date or time. Like, I wanted yesterday's date in a particular format. You may want the exact date of "2 months ago" or "-3 days" nicely formatted. For that, you can use this command. The --date option takes fuzzy parameters like the ones mentioned in the previous sentence.

0 0 * * 0 /usr/bin/mysqldump -uroot -p'<password>' data_base_name > /home/bob/XYZ_DB_BACKUP/$(date +\%Y-\%m-\%d_\%Hh\%M).sql
2010-09-02 20:07:07
User: dtolj
Functions: date
0

Create a cronjob that runs weekly to backup your database to a file.

jb() { if [ -z $1 ];then printf 'usage:\njb <"date and/or time"> <"commandline"> &\nsee parsedate(3) strftime(3)\n';else t1=$(date +%s); t2=$(date -d "$1" +%s) ;sleep $(expr $t2 - $t1);$2 ;fi ;}
2010-08-26 23:50:42
User: argv
Functions: date expr printf
2

EXAMPLES

jb "next sun 12pm" "/bin/sh ~you/1.sh" &

jb "2010-08-29 12:00:00" "~you/1.sh" &

jb "29aug2010 gmt" ". ~you/1.sh" &

jb 12:00p.m. "nohup ./1.sh" &

jb 1min "echo stop!" &

SEE ALSO

parsedate(3) strftime(3)

rsync -av --link-dest=$(ls -1d /backup/*/ | tail -1) /data/ /backup/$(date +%Y%m%d%H%M)/
2010-08-05 19:36:24
User: dooblem
Functions: date ls rsync tail
Tags: backup rsync
1

'data' is the directory to backup, 'backup' is directory to store snapshots.

Backup files on a regular basis using hard links. Very efficient, quick. Backup data is directly available.

Same as explained here :

http://blog.interlinked.org/tutorials/rsync_time_machine.html

in one line.

Using du to check the size of your backups, the first backup counts for all the space, and other backups only files that have changed.

ls -la | grep $(date +%Y-%m-%d) | egrep -v -e '\.{1,2}' | sed "s/.*\:[0-9]\{2\} \(.\+\)$/\\1/g"
truss date 2>&1 | awk '/^time/{print $3}'
TZ=PST8PDT+72 date '+%Y_%m_%d'
2010-07-02 00:29:27
Functions: date
Tags: date nongnu
4

This command prints the Date (Not time) from 3 days ago (72 hours ago).

This works on systems without GNU date (MacOSX , Solaris, FreeBSD).