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 - 707 results
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.

declare -f [ function_name ]
set | fgrep " ()"
2009-10-22 17:48:54
User: haivu
Functions: fgrep set
1

If you issue the "set" command, you'll see a list of variables and functions. This command displays just those functions' names.

sed -n '/^function h\(\)/,/^}/p' script.sh
2009-10-19 07:55:35
User: haivu
Functions: sed
Tags: bash sed
8

I often need to extract a function from a bash script and this command will do it.

argv=("$@"); rest=${argv[@]:1}; less -JMN +"/$1" `grep -l $1 $rest`
2009-10-16 17:36:16
User: lassel
Functions: less
Tags: bash less log grep
1

Really useful way to combine less and grep while browsing log files.

I can't figure out how to make it into a true oneliner so paste it into a script file called lgrep:

Usage:

lgrep searchfor file1 [file2 file3]

Advanced example (grep for an Exception in logfiles that starts with qc):

lgrep Exception $(find . -name "qc*.log")

PROMPT_COMMAND=command
2009-10-15 06:01:18
User: haivu
Tags: bash prompt
1

For example, if you are the type who type ls very often, then

PROMPT_COMMAND=ls

will ls after every command you issue.

h() { if [ -z "$1" ]; then history; else history | grep "$@"; fi; }
2009-10-13 21:49:37
User: haivu
Functions: grep
Tags: bash grep
6

Place this in your .bash_profile and you can use it two different ways. If you issue 'h' on its own, then it acts like the history command. If you issue:

h cd

Then it will display all the history with the word 'cd'

ping -q -c1 -w3 brandx.jp.sme 2&>1 /dev/null || echo brandx.jp.sme ping failed | mail -ne -s'Server unavailable' joker@jp.co.uk
2009-10-13 14:13:04
User: mccalni
Functions: echo mail ping
Tags: bash ping mail
7

Joker wants an email if the Brand X server is down. Set a cron job for every 5 mins with this line and he gets an email when/if a ping takes longer than 3 seconds.