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.


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:



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.




Commands tagged function from sorted by
Terminal - Commands tagged function - 108 results
bm() { export BM${1?"bookmark name missing"}="$PWD" ; }; forget() { unset BM${1?"bookmark name missing"} ; }
2010-11-19 12:15:11
User: unefunge
Functions: export unset

pushd and popd are your friends, but sometimes they're just incompatible with the way one works...

Two shell functions:

bm bookmarkname - "bookmarks" the current directory, just 'cd $BMbookmarkname' to return to it.

forget bookmarkname - unsets the 'bookmarkname' variable. It isn't mandatory, they cease to exist when the session ends.

wget -O xkcd_$(date +%y-%m-%d).png `lynx --dump http://xkcd.com/|grep png`; eog xkcd_$(date +%y-%m-%d).png
for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv

This uses some tricks I found while reading the bash man page to enumerate and display all the current environment variables, including those not listed by the 'env' command which according to the bash docs are more for internal use by BASH. The main trick is the way bash will list all environment variable names when performing expansion on ${!A*}. Then the eval builtin makes it work in a loop.

I created a function for this and use it instead of env. (by aliasing env).

This is the function that given any parameters lists the variables that start with it. So 'aae B' would list all env variables starting wit B. And 'aae {A..Z} {a..z}' would list all variables starting with any letter of the alphabet. And 'aae TERM' would list all variables starting with TERM.

aae(){ local __a __i __z;for __a in "$@";do __z=\${!${__a}*};for __i in `eval echo "${__z}"`;do echo -e "$__i: ${!__i}";done;done; }

And my printenv replacement is:

alias env='aae {A..Z} {a..z} "_"|sort|cat -v 2>&1 | sed "s/\\^\\[/\\\\033/g"'

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

atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.tar.gz} && tar xf $1 -C ${1%.tar.gz}; fi ;}
2010-10-16 05:50:32
User: elfreak
Functions: echo grep head mkdir tar wc

This Anti-TarBomb function makes it easy to unpack a .tar.gz without worrying about the possibility that it will "explode" in your current directory. I've usually always created a temporary folder in which I extracted the tarball first, but I got tired of having to reorganize the files afterwards. Just add this function to your .zshrc / .bashrc and use it like this;

atb arch1.tar.gz

and it will create a folder for the extracted files, if they aren't already in a single folder.

This only works for .tar.gz, but it's very easy to edit the function to suit your needs, if you want to extract .tgz, .tar.bz2 or just .tar.

More info about tarbombs at http://www.linfo.org/tarbomb.html

Tested in zsh and bash.

UPDATE: This function works for .tar.gz, .tar.bz2, .tgz, .tbz and .tar in zsh (not working in bash):

atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.t(ar.gz||ar.bz2||gz||bz||ar)} && tar xf $1 -C ${1%.t(ar.gz||ar.bz2||gz||bz||ar)}; fi ;}

UPDATE2: From the comments; bepaald came with a variant that works for .tar.gz, .tar.bz2, .tgz, .tbz and .tar in bash:

atb() {shopt -s extglob ; l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.t@(ar.gz|ar.bz2|gz|bz|ar)} && tar xf $1 -C ${1%.t@(ar.gz|ar.bz2|gz|bz|ar)}; fi ; shopt -u extglob}
for p in `ps L|cut -d' ' -f1`;do echo -e "`tput clear;read -p$p -n1 p`";ps wwo pid:6,user:8,comm:10,$p kpid -A;done

While going through the source code for the well known ps command, I read about some interesting things.. Namely, that there are a bunch of different fields that ps can try and enumerate for you. These are fields I was not able to find in the man pages, documentation, only in the source.

Here is a longer function that goes through each of the formats recognized by the ps on your machine, executes it, and then prompts you whether you would like to add it or not. Adding it simply adds it to an array that is then printed when you ctrl-c or at the end of the function run. This lets you save your favorite ones and then see the command to put in your .bash_profile like mine at : http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

Note that I had to do the exec method below in order to pause with read.

t ()


local r l a P f=/tmp/ps c='command ps wwo pid:6,user:8,vsize:8,comm:20' IFS=' ';

trap 'exec 66

exec 66 $f && command ps L | tr -s ' ' >&$f;

while read -u66 l >&/dev/null; do

a=${l/% */};

$c,$a k -${a//%/} -A;

yn "Add $a" && P[$SECONDS]=$a;



awk "BEGIN{ print $* }"
2010-10-07 16:13:41
User: maelcum
Functions: awk

works with fractions like 1/3.5

calc() { bc <<< $*; }
calc() { python -c "from math import *; print $1"; }
2010-10-07 08:26:39
User: asmaier
Functions: python

This function defines a command line calculator that handles everything pythons math module can handle, e.g. trigonometric functions, sqrt, log, erf, ... (see http://docs.python.org/library/math.html). It even knows about the constants pi and e.

shout() { curl -s "http://shoutkey.com/new?url=${1}" | sed -n "/<h1>/s/.*href=\"\([^\"]*\)\".*/\1/p" ;}
shout () { curl -s "http://shoutkey.com/new?url=$1" | sed -n 's/\<h1\>/\&/p' | sed 's/<[^>]*>//g;/</N;//b' ;}
2010-10-04 23:50:54
User: elfreak
Functions: sed

Just add this function to your .zshrc / .bashrc, and by typing "shout *URL*" you get a randomly chosen English word that ShoutKey.com uses to short your URL. You may now go to shoutkey.com/*output_word* and get redirected. The URL will be valid for 5 minutes.

(I've never used sed before, so I'll be quite glad if someone could straighten up the sed commands and combine them (perhaps also removing the whitespace). If so, I'll update it right away ;) )

yt () mplayer -fs -quiet $(youtube-dl -g "$1")
2010-09-29 18:48:19
User: elfreak

A function for streaming youtube to mplayer.

The option "-g" for youtube-dl tells it to output the direct video URL, instead of downloading the video.

"-fs" tells MPlayer to go FullScreen, and "-quit" makes it less verbose.

Requires: youdube-dl ( http://bitbucket.org/rg3/youtube-dl/ )

(Tested in zsh)

eog `curl -s http://xkcd.com/ | sed -n 's/<h3>Image URL.*: \(.*\)<\/h3>/\1/p'`
xdg-open http://xkcd.com/
2010-08-25 19:14:11


To get a random xkcd comic:

xdg-open http://dynamic.xkcd.com/random/comic/
xkcd() { wget -qO- http://xkcd.com/ | sed -n 's#^<img src="\(http://imgs.[^"]\+\)"\s\+title="\(.\+\?\)"\salt.\+$#eog "\1"\necho '"'\2'#p" | bash ; }
2010-08-25 15:44:31
User: John_W
Functions: bash sed wget

This function displays the latest comic from xkcd.com. One of the best things about xkcd is the title text when you hover over the comic, so this function also displays that after you close the comic.

To get a random xkcd comic use the following:

xkcdrandom() { wget -qO- http://dynamic.xkcd.com/comic/random | sed -n 's#^<img src="\(http://imgs.[^"]\+\)"\s\+title="\(.\+\?\)"\salt.\+$#eog "\1"\necho '"'\2'#p" | bash; }

These are just a bit shorter than the ones eigthmillion wrote, however his version didn't work as expected on my laptop for some reason (I got the title-tag first), so these build a command which is executed by bash.

eog `curl 'http://xkcd.com/' | awk -F "ng): |</h" '/embedding/{print $2}'`
gwenview `wget -O - http://xkcd.com/ | grep 'png' | grep '<img src="http://imgs.xkcd.com/comics/' | sed s/title=\".*//g | sed 's/.png\"/.png/g' | sed 's/<img src=\"//g'`
2010-08-24 22:21:51
User: hunterm
Functions: grep sed

Output the html from xkcd's index.html, filter out the html tags, and then view it in gwenview.

s="StrinG"; echo ${s,,}
2010-08-12 16:02:38
User: karpoke
Functions: echo
Tags: bash function

Another alternative is to define a function:

lower() {

echo ${@,,}


lower StrinG

__disown(){ local cmd=$1 ; shift ; $cmd "$@" &> /dev/null &disown }; for i in gvim ; do alias $i="__disown $i"; done
2010-07-07 20:46:45
User: smolav
Functions: alias shift
Tags: bash function

Define commands that you always invoke with an appended '&disown'. In the example:

gvim foo.txt

will open gvim dettached from the current terminal.

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

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


addman () { export MANPATH=`find $1 -xdev -type d -name man -printf %p:`${MANPATH}; }
2010-06-12 17:47:20
User: zoomgarden
Functions: export man
Tags: man function

Prepends paths containing man directories to your MANPATH variable for the given top level directory. If you build or install software with non-standard documentation locations, you can just add them to your MANPATH with this little function. -xdev prevents crossing filesystem boundaries when searching for man dirs.

quickfind () { find . -maxdepth 2 -iname "*$1*" }
2010-06-12 03:04:50
User: dbbolton
Functions: find
Tags: find function

A function that allows you to perform a case-insensitive search in the current directory, and directories in the current directory (but no further), for files containing the first argument anywhere in their names.

statt(){ C=c;stat --h|sed '/Th/,/NO/!d;/%/!d'|while read l;do p=${l/% */};[ $p == %Z ]&&C=fc&&echo ^FS:^;echo "`stat -$C $p \"$1\"` ^$p^${l#%* }";done|column -ts^; }
2010-06-11 23:31:03
User: AskApache
Functions: column read sed

This shows every bit of information that stat can get for any file, dir, fifo, etc. It's great because it also shows the format and explains it for each format option.

If you just want stat help, create this handy alias 'stath' to display all format options with explanations.

alias stath="stat --h|sed '/Th/,/NO/!d;/%/!d'"

To display on 2 lines:

( F=/etc/screenrc N=c IFS=$'\n'; for L in $(sed 's/%Z./%Z\n/'<<<`stat --h|sed -n '/^ *%/s/^ *%\(.\).*$/\1:%\1/p'`); do G=$(echo "stat -$N '$L' \"$F\""); eval $G; N=fc;done; )

For a similarly powerful stat-like function optimized for pretty output (and can sort by any field), check out the "lll" function


From my .bash_profile ->


find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'

I love this function because it tells me everything I want to know about files, more than stat, more than ls. It's very useful and infinitely expandable.

find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' | sort -rgbS 50%

00761 drwxrw---x askapache:askapache 777:666 [06/10/10 | 06/10/10 | 06/10/10] [d] /web/cg/tmp

The key is:

# -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'

which believe it or not took me hundreds of tweaking before I was happy with the output.

You can easily use this within a function to do whatever you want.. This simple function works recursively if you call it with -r as an argument, and sorts by file permissions.

lsl(){ O="-maxdepth 1";sed -n '/-r/!Q1'<<<$@ &&O=;find $PWD $O -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -rgbS 50%; }

Personally I'm using this function because:

lll () { local a KS="1 -r -g"; sed -n '/-sort=/!Q1' <<< $@ && KS=`sed 's/.*-sort=\(.*\)/\1/g'<<<$@`; find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -k$KS -bS 50%; }

# i can sort by user

lll -sort=3

# or sort by group reversed

lll -sort=4 -r

# and sort by modification time

lll -sort=6

If anyone wants to help me make this function handle multiple dirs/files like ls, go for it and I would appreciate it.. Something very minimal would be awesome.. maybe like:

for a; do lll $a; done

Note this uses the latest version of GNU find built from source, easy to build from gnu ftp tarball. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

declare -F | cut -d ' ' -f 3
sortwc () { local L;while read -r L;do builtin printf "${#L}@%s\n" "$L";done|sort -n|sed -u 's/^[^@]*@//'; }
2010-05-20 20:13:52
User: AskApache
Functions: printf read sed sort

This provides a way to sort output based on the length of the line, so that shorter lines appear before longer lines. It's an addon to the sort that I've wanted for years, sometimes it's very useful. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html