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 tagged bash from sorted by
Terminal - Commands tagged bash - 714 results
lynx --dump --source http://www.xkcd.com | grep `lynx --dump http://www.xkcd.com | egrep '(png|jpg)'` | grep title | cut -d = -f2,3 | cut -d '"' -f2,4 | sed -e 's/"/|/g' | awk -F"|" ' { system("display " $1);system("echo "$2); } '
2009-12-03 18:53:57
Functions: awk cut egrep grep
-1

Same thing just a different way to get there. You will need lynx

some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr)
2009-12-01 03:58:04
User: tylerl
25

You can use [n]> combined with >(cmd) to attach the various output file descriptors to be the input of different commands.

sudo echo 0 > /sys/block/sdb/queue/rotational
2009-11-27 12:16:17
User: nickleus
Functions: echo sudo
5

if you still get a permissions error using sudo, then nano the file:

sudo nano -w /sys/block/sdb/queue/rotational

and change 1 to 0

this thread:

http://www.ocztechnologyforum.com/forum/showpost.php?p=369836&postcount=15

says that this will "help the block layer to optimize a few decisions"

iostat -m -d /dev/sda1
2009-11-27 12:00:48
User: nickleus
3

The iostat command is used for monitoring system input/output device loading by observing the time the devices are active in relation to their average transfer rates.

in ubuntu to get the iostat program do this:

sudo apt-get install sysstat

i found this command here:

http://www.ocztechnologyforum.com/forum/showthread.php?t=54379

xkcd(){ wget -qO- http://xkcd.com/|tee >(feh $(grep -Po '(?<=")http://imgs[^/]+/comics/[^"]+\.\w{3}'))|grep -Po '(?<=(\w{3})" title=").*(?=" alt)';}
2009-11-27 09:11:47
User: eightmillion
Functions: grep tee wget
24

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, I also use the following:

xkcdrandom(){ wget -qO- dynamic.xkcd.com/comic/random|tee >(feh $(grep -Po '(?<=")http://imgs[^/]+/comics/[^"]+\.\w{3}'))|grep -Po '(?<=(\w{3})" title=").*(?=" alt)';}
colordiff -yW"`tput cols`" /path/to/file1 /path/to/file2
2009-11-26 18:00:53
User: dweomer21
9

Barely worth posting because it is so simple, but I use it literally all the time. I was always frustrated by the limitations that a non-gui environment imposes on diff'ing files. This fixes some of those limitations by colourising the output (you'll have to install colordiff, but it is just a wrapper for diff itself), using side-by-side mode for clearer presentation, and of course, the -W parameter, using tput to automatically insert you terminal width. Note that the double quotes aren't necessary if typed into terminal as-is. I included them for safety sake,

process-getopt
2009-11-25 06:48:37
User: bhepple
Tags: bash getopt
1

This will make your bash scripts better!!

process-getopt is a wrapper around getopt(1) for bash that lets you define command line options (eg -h, --help) and descriptions through a single function call. These definitions are then used in runtime processing of command line options as well as in generating help and man pages. It also saves a little time in coding and in producing nicely formatted documentation. It is quite similar to GNU's argp in glibc for compiled languages and OptionParse for python.

See: Linux Gazette article 162: http://tldp.org/LDP/LGNET/162/hepple.html,

http://sourceforge.net/projects/process-getopt, http://bhepple.freeshell.org/oddmuse/wiki.cgi/process-getopt

printf $(echo -n $1 | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')
2009-11-25 04:27:39
User: infinull
Functions: echo printf sed
2

My version uses printf and command substitution ($()) instead of echo -e and xargs, this is a few less chars, but not real substantive difference.

Also supports lowercase hex letters and a backslash (\) will make it through unescaped

function decToBin { echo "ibase=10; obase=2; $1" | bc; }
2009-11-24 22:57:58
User: woxidu
Functions: echo
3

Convert some decimal numbers to binary numbers. You could also build a general base-converter:

function convBase { echo "ibase=$1; obase=$2; $3" | bc; }

then you could write

function decToBun { convBase 10 2 $1; }
awk '/q=/{print $11}' /var/log/httpd/access_log.4 | awk -F 'q=' '{print $2}' | sed 's/+/ /g;s/%22/"/g;s/q=//' | cut -d "&" -f 1
cat /var/log/httpd/access_log | grep q= | awk '{print $11}' | awk -F 'q=' '{print $2}' | sed 's/+/ /g;s/%22/"/g;s/q=//' | cut -d "&" -f 1 | mail youremail@isp.com -s "[your-site] search strings for `date`"
2009-11-22 03:03:06
User: isma
Functions: awk cat grep sed strings
-2

It's not a big line, and it *may not* work for everybody, I guess it depends on the detail of access_log configuration in your httpd.conf. I use it as a prerotate command for logrotate in httpd section so it executes before access_log rotation, everyday at midnight.

(echo CD_DA; for f in {01..99}; do echo "$f Hz">&2; sox -nt cdda -r44100 -c2 $f.cdda synth 30 sine $f; echo TRACK AUDIO; echo FILE \"$f.cdda\" 0; done) > cdrdao.toc && cdrdao write cdrdao.toc && rm ??.cdda cdrdao.toc
2009-11-17 06:23:42
User: hackerb9
Functions: cdrdao echo rm write
21

This command creates and burns a gapless audio CD with 99 tracks. Each track is a 30 second sine wave, the first is 1 Hz, the second 2 Hz, and so on, up to 99 Hz. This is useful for testing audio systems (how low can your bass go?) and for creating the constant vibrations needed to make non-Newtonian fluids (like cornstarch and water) crawl around.

Note, this temporarily creates 500MB of .cdda files in the current directory. If you don't use the "rm" at the end of the command, you can burn more disks using

cdrdao write cdrdao.toc

Prerequisites: a blank CD-R in /dev/cdrw, sox (http://sox.sourceforge.net/), and cdrdao (http://cdrdao.sourceforge.net/). I'm also assuming a recent version of bash for the brace expansion (which just looks nicer than using seq(1), but isn't necessary).

albumart(){ local y="$@";awk '/View larger image/{gsub(/^.*largeImagePopup\(.|., .*$/,"");print;exit}' <(curl -s 'http://www.albumart.org/index.php?srchkey='${y// /+}'&itempage=1&newsearch=1&searchindex=Music');}
2009-11-15 19:54:16
User: eightmillion
7

This bash function uses albumart.org to find the cover for an album. It returns an amazon.com url to the image.

Usage: albumart [artist] [album]

These arguments can be reversed and if the album name is distinct enough, it may be possible to omit the artist.

The command can be extended with wget to automatically download the matching image like this:

albumart(){ local x y="$@";x=$(awk '/View larger image/{gsub(/^.*largeImagePopup\(.|., .*$/,"");print;exit}' <(curl -s 'http://www.albumart.org/index.php?srchkey='${y// /+}'&itempage=1&newsearch=1&searchindex=Music'));[ -z "$x" ]&&echo "Not found."||wget "$x" -O "${y}.${x##*.}";}
psu(){ command ps -Hcl -F S f -u ${1:-$USER}; }
2009-11-13 06:10:33
User: AskApache
Functions: command ps
4

An easy function to get a process tree listing (very detailed) for all the processes of any gived user.

This function is also in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

curl -s -c /tmp/cookie -k -u tivo:$MAK --digest http://$tivo/download/$filename | tivodecode -m $MAK -- - | mplayer - -cache-min 50 -cache 65536
flac --best *.wav
2009-11-11 14:17:24
User: nickleus
Tags: bash Ubuntu
2

cd to the folder containing the wav files, then convert them all to flac. yeah baby!

in ubuntu, to get the flac program just:

sudo apt-get install flac

flac file input formats are wav, aiff, raw, flac, oga and ogg

find . -mmin -60 -not -path "*svn*" -print|more
2009-11-10 18:34:53
User: bloodykis
Functions: find
Tags: bash svn find
2

Find files recursively that were updated in the last hour ignoring SVN files and folders. Incase you do a full svn up on accident.

read -sn 1 -p 'Press any key to continue...';echo
for c in `seq 0 255`;do t=5;[[ $c -lt 108 ]]&&t=0;for i in `seq $t 5`;do echo -e "\e[0;48;$i;${c}m|| $i:$c `seq -s+0 $(($COLUMNS/2))|tr -d '[0-9]'`\e[0m";done;done
2009-11-03 09:12:13
User: AskApache
Functions: c++ echo
15

I've been using linux for almost a decade and only recently discovered that most terminals like putty, xterm, xfree86, vt100, etc., support hundreds of shades of colors, backgrounds and text/terminal effects.

This simply prints out a ton of them, the output is pretty amazing.

If you use non-x terminals all the time like I do, it can really be helpful to know how to tweak colors and terminal capabilities. Like:

echo $'\33[H\33[2J'
newest () { candidate=''; for i in "$@"; do [[ -f $i ]] || continue; [[ -z $candidate || $i -nt $candidate ]] && candidate="$i"; done; echo "$candidate"; }
2009-10-29 17:35:01
User: johnraff
Functions: echo
Tags: bash files
1

Usage example:

newest Desktop/*

Replace "-nt" with "-ot" for oldest.

Run

shopt -s dotglob

first to include dotfiles.

echo {001..5}
2009-10-29 16:25:44
User: nanard06
Functions: echo
Tags: bash
5

bash2 : for X in $(seq 1 5); do printf "%03g " "$X";done

bash3 : for X in {1..5}; do printf "%03g " "$X";done

bash4 : echo {001..5}

shopt -s cdable_vars
2009-10-26 22:10:56
User: haivu
Tags: bash shell
4

Usage:

mydir=/very/long/path/to/a/dir cd mydir

I often need to cd where no man wants to go (i.e. long path). by enabling the shell option cdable_vars, I can tell cd to assume the destination is the name of a variable.

ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub && ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub
2009-10-26 17:52:41
Functions: ssh ssh-keygen
Tags: ssh bash
4

Get your server's fingerprints to give to users to verify when they ssh in. Publickey locations may vary by distro. Fingerprints should be provided out-of-band.

declare -F | sed 's/^declare -f //'
curl -fs brandx.jp.sme 2&>1 > /dev/null || echo brandx.jp.sme ping failed | mail -ne -s'Server unavailable' joker@jp.co.uk
2009-10-23 14:29:06
User: mccalni
Functions: echo mail ping
Tags: bash ping curl mail
2

Alternative to the ping check if your firewall blocks ping. Uses curl to get the landing page silently, or fail with an error code. You can probably do this with wget as well.