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 printf from sorted by
Terminal - Commands using printf - 155 results
p(){ c=$(($(tput cols)-3));j=$(($1*c/100)); tput sc;printf "[$(for((k=0;k<j;k++));do printf "=";done;)>";tput cuf $((c-j));printf "]";tput rc; };for((i=0; i<=100; i++));do p i;done;echo
2011-02-20 02:17:05
User: glaudiston
Functions: printf tput
2

A simple way yo do a progress bar like wget.

yes 'clear;printf "`date`\n" | figlet -f starwars | boxes;sleep 1' | sh
2011-02-16 03:58:19
User: lkjoel
Functions: printf sleep yes
0

This is a different version from my original command: Console clock -- Beautiful (http://www.commandlinefu.com/commands/view/7902/console-clock-beautiful )

This one uses Boxes and Figlet.

To install the dependencies on Ubuntu, type in:

sudo apt-get install boxes figlet

To install the dependencies on Debian, type in:

aptitude install boxes figlet
yes 'clear;printf "\n\n`date`\n" | figlet -f starwars;sleep 1' | sh
2011-02-16 03:05:52
User: lkjoel
Functions: printf sleep yes
1

This will show a console clock with Figlet.

This is with the Star Wars font.

Change the -f option to anything else.

Notice: You need Figlet installed for this to work.

To install Figlet on Ubuntu, type in:

sudo apt-get install figlet

To install Figlet on Debian, type in:

aptitude install figlet
yes 'clear;printf "\n\n\n\n\t\t\t`date`\n";sleep 1' | sh
2011-02-16 02:57:16
User: lkjoel
Functions: printf sleep yes
2

This command will automatically clear the old clock time, and show the new clock time.

It will also slightly format it.

awk ' { printf ("%s ", $0)} END {printf ("\n") } ' FILE
2011-02-02 11:51:41
User: bouktin
Functions: awk printf
Tags: awk
-1

remove all carriage return of a given file (or input, if used with | ) and replace them with a space (or whatever character is after %s)

println() {echo -n -e "\e[038;05;${2:-255}m";printf "%$(tput cols)s"|sed "s/ /${1:-=}/g"}
2011-01-09 18:08:18
User: joedhon
Functions: printf sed
Tags: sed tput printf
0

function for .bash_aliases that prints a line of the character of your choice in the color of your choice across the terminal.

Default character is "=", default color is white.

for i in {1..6}; do printf "%0.2X:" $[ $RANDOM % 0x100 ]; done | sed 's/:$/\n/'
2010-12-07 19:26:58
User: forcefsck
Functions: printf sed
Tags: Network bash mac
2

Shorter and more straightforward.

Also in perl:

perl -e 'print join(":", map { sprintf "%0.2X",rand(256) }(1..6))."\n"'
alias duh='dulist=$(du -sh */); for i in T G M K; do printf "$dulist"|egrep "^[0-9\.]+$i" | sort -rn; done'
2010-12-07 11:11:26
User: forcefsck
Functions: alias du egrep printf sort
Tags: disk usage
-1

Alias to produce a list of all subdir sizes in current dir, in reverse order and human readable units. du is executed only once. Remove the slash after the asterisk to include files.

printf "$string" | md5sum
tail -f file |xargs -IX printf "$(date -u)\t%s\n" X
echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=' ') f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*"
2010-11-24 23:49:21
User: unefunge
Functions: echo printf tr xargs
4

displays current time in "binary clock" format

(loosely) inspired by: http://www.thinkgeek.com/homeoffice/lights/59e0/

"Decoding":

8421

.... - 1st hour digit: 0

*..* - 2nd hour digit: 9 (8+1)

.*.. - 1st minutes digit: 4

*..* - 2nd minutes digit: 9 (8+1)

Prompt-command version:

PROMPT_COMMAND='echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=" ") f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*"'

PROMPT_COMMAND='seq $COLUMNS | xargs -IX printf "%Xs\r" @'
tail -f file | while read line; do printf "$(date -u '+%F %T%z')\t$line\n"; done
2010-11-24 05:50:12
User: derekschrock
Functions: file printf read tail
Tags: tail date
4

Should be a bit more portable since echo -e/n and date's -Ins are not.

for file in $( vmrun list | grep 'vmx$' | sort ); do printf "% 40s %s M\n" $(echo "$( echo -n ${file}:\ ; grep memsize $file )" | sed -e 's/.*\///' -e 's/"//g' -e 's/memsize.=//'); done;
2010-11-19 06:14:11
Functions: echo file grep printf sed sort
Tags: vmware
-1

So your boss wants to know how much memory has been assigned to each virtual machine running on your server... here's how to nab that information from the command line while logged in to that server

for i in ???.jpg; do mv $i $(printf %04d $(basename $i .jpg) ).jpg ; done
2010-11-18 23:48:41
User: carlesso
Functions: basename mv printf
Tags: rename cp printf
5

Useful if you have a list of images called 1 2 3 4 and so on, you can adapt it to rewrite it as 4 (in this example) 0-padded number.

OFFS=30;LZ=6;FF=$(printf %%0%dd $LZ);for F in *.jpg;do NF="${F%.jpg}";NF="${NF/#+(0)/}";NF=$[NF+OFFS];NF="$(printf $FF $NF)".jpg;if [ "$F" != "$NF" ];then mv -iv "$F" "$NF";fi;done
2010-11-08 22:48:56
Functions: mv printf
2

When you have different digital cameras, different people, friends and you want to merge all those pictures together, then you get files with same names or files with 3 and 4 digit numbers etc. The result is a mess if you copy it together into one directory.

But if you can add an offset to the picture number and set the number of leading zeros in the file name's number then you can manage.

OFFS != 0 and LZ the same as the files currently have is not supported. Or left as an exercise, hoho ;)

I love NF="${NF/#+(0)/}",it looks like a magic bash spell.

mplayer -vo null -ao null -frames 0 -identify movie.avi | awk '{FS="="}; /ID_LENGTH/{ H=int($2/3600); M=int(($2-H*3600)/60); S=int($2%60); printf "%d:%02d:%02d\n",H,M,S}'
2010-10-13 14:51:41
User: PNuts
Functions: awk printf
0

Prints movie length in H:MM:SS format with appropriate leading zeros.

rd(){ while read a ;do printf "$a\n";sleep ${1-1};done ;} # usage: rd < file ; or ... | rd
2010-10-03 04:16:03
User: argv
Functions: file printf read sleep
2

usage examples

ls largedir |rd

lynx -dump largewebsite.com |rd

rd < largelogfile

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)

cls(){ printf "\033c";} or, if no printf, cat > c ;<ctrl+v> <ctrl+[>c <enter><ctrl-d> c(){ cat c;} #usage: c
printf $(( echo "obase=16;$(echo $$$(date +%s%N))"|bc; ip link show|sed -n '/eth/ {N; p}'|grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'|head -c 17 )|tr -d [:space:][:punct:] |sed 's/[[:xdigit:]]\{2\}/\\x&/g')|sha1sum|head -c 32; echo
2010-07-14 14:04:53
User: camocrazed
Functions: echo grep head link printf sed tr
Tags: uuid
0

first off, if you just want a random UUID, here's the actual command to use:

uuidgen

Your chances of finding a duplicate after running this nonstop for a year are about the same as being hit by a meteorite before finishing this sentence

The reason for the command I have is that it's more provably unique than the one that uuidgen creates. uuidgen creates a random one by default, or an unencrypted one based on time and network address if you give it the -t option.

Mine uses the mac address of the ethernet interface, the process id of the caller, and the system time down to nanosecond resolution, which is provably unique over all computers past, present, and future, subject to collisions in the cryptographic hash used, and the uniqueness of your mac address.

Warning: feel free to experiment, but be warned that the stdin of the hash is binary data at that point, which may mess up your terminal if you don't pipe it into something. If it does mess up though, just type

reset
echo "${1}" | egrep '^[[:digit:]]*$' ; if [ "$?" -eq 0 ] ; then sed -i "${1}"d $HOME/.ssh/known_hosts ; else printf "\tYou must enter a number!\n\n" ; exit 1 ; fi
2010-07-11 23:09:11
User: DaveQB
Functions: echo egrep exit printf sed
Tags: sed
-13

I have this as a file called deletekey in my ~/bin.

Makes life a little easier.

grep '^MemFree:' /proc/meminfo | awk '{ mem=($2)/(1024) ; printf "%0.0f MB\n", mem }'
2010-06-30 18:33:29
User: dbbolton
Functions: awk grep printf
4

This will show the amount of physical RAM that is left unused by the system.

L(){ l=`builtin printf %${2:-$COLUMNS}s` && echo -e "${l// /${1:-=}}"; }
2

One of the first functions programmers learn is how to print a line. This is my 100% bash builtin function to do it, which makes it as optimal as a function can be. The COLUMNS environment variable is also set by bash (including bash resetting its value when you resize your term) so its very efficient. I like pretty-output in my shells and have experimented with several ways to output a line the width of the screen using a minimal amount of code. This is like version 9,000 lol.

This function is what I use, though when using colors or other terminal features I create separate functions that call this one, since this is the lowest level type of function. It might be better named printl(), but since I use it so much it's more optimal to have the name contain less chars (both for my programming and for the internal workings).

If you do use terminal escapes this will reset to default.

tput sgr0

For implementation ideas, check my

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

echo -n "convert " > itcombino.sh; printf "IMG_%00004u.png " {1..1121} >> itcombino.sh; echo -n "-layers merge _final.png" >> itcombino.sh; chmod +x itcombino.sh && ./itcombino.sh
2010-05-22 03:56:30
User: IsraelTorres
Functions: chmod echo printf
1

This one liner; combines all sequentially numbered files; in this example IMG_0001.png to IMG_1121.png by generating the shell script, making the shell script executable and then running the shell script to combine the 1121 png into a single png file named _final.png

tested on Mac OS X 10.6.3 with ImageMagick 6.5.8-0 2009-11-22 Q16 http://www.imagemagick.org