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 bash from sorted by
Terminal - Commands tagged bash - 716 results
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

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

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

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

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:


lgrep searchfor file1 [file2 file3]

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

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

2009-10-15 06:01:18
User: haivu
Tags: bash prompt

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


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

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

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.

( trap '' 1; ( nice -n 19 sleep 2h && command rm -v -rf /garbage/ &>/dev/null && trap 1 ) & )

Check out the usage of 'trap', you may not have seen this one much. This command provides a way to schedule commands at certain times by running them after sleep finishes sleeping. In the example 'sleep 2h' sleeps for 2 hours. What is cool about this command is that it uses the 'trap' builtin bash command to remove the SIGHUP trap that normally exits all processes started by the shell upon logout. The 'trap 1' command then restores the normal SIGHUP behaviour.

It also uses the 'nice -n 19' command which causes the sleep process to be run with minimal CPU.

Further, it runs all the commands within the 2nd parentheses in the background. This is sweet cuz you can fire off as many of these as you want. Very helpful for shell scripts.

sed -i '19375 s/^/#/' file
2009-10-07 17:50:40
User: TuxOtaku
Functions: sed

This will comment out a line, specified by line number, in a given file.

env PS4=' ${BASH_SOURCE}:${LINENO}(${FUNCNAME[0]}) ' sh -x /etc/profile
su -- user
2009-09-28 04:23:43
User: matthewdavis
Functions: su
Tags: bash root su

I've used this a number of times troubleshooting user permissions. Instead of just 'su - user' you can throw another hyphen and stay in the original directory.

md () { mkdir -p "$@" && cd "$@"; }
2009-09-24 16:09:19
User: drewk
Functions: cd mkdir

How often do you make a directory (or series of directories) and then change into it to do whatever? 99% of the time that is what I do.

This BASH function 'md' will make the directory path then immediately change to the new directory. By using the 'mkdir -p' switch, the intermediate directories are created as well if they do not exist.

grep -RnisI <pattern> *
2009-09-22 15:09:43
User: birnam
Functions: grep
Tags: bash grep

This is how I typically grep. -R recurse into subdirectories, -n show line numbers of matches, -i ignore case, -s suppress "doesn't exist" and "can't read" messages, -I ignore binary files (technically, process them as having no matches, important for showing inverted results with -v)

I have grep aliased to "grep --color=auto" as well, but that's a matter of formatting not function.

`pbpaste` | pbcopy
2009-09-21 23:10:11
User: drewk
Tags: Os X bash osx pipes

The backtick operator, in general, will execute the text inside the backticks. On OS X, the pbpaste command will put the contents of the OS X clipboard to STDOUT. So if you put backticks around pbpaste, the text from the OS X clipboard is executed.

If you add the pipeline | pbcopy, the output from executing the command on the clipboard is placed back on the clipboard.

Note: make sure the clipboard is text only.

find $HOME -type f -print0 | perl -0 -wn -e '@f=<>; foreach $file (@f){ (@el)=(stat($file)); push @el, $file; push @files,[ @el ];} @o=sort{$a->[9]<=>$b->[9]} @files; for $i (0..$#o){print scalar localtime($o[$i][9]), "\t$o[$i][-1]\n";}'|tail
2009-09-21 22:11:16
User: drewk
Functions: find perl

This pipeline will find, sort and display all files based on mtime. This could be done with find | xargs, but the find | xargs pipeline will not produce correct results if the results of find are greater than xargs command line buffer. If the xargs buffer fills, xargs processes the find results in more than one batch which is not compatible with sorting.

Note the "-print0" on find and "-0" switch for perl. This is the equivalent of using xargs. Don't you love perl?

Note that this pipeline can be easily modified to any data produced by perl's stat operator. eg, you could sort on size, hard links, creation time, etc. Look at stat and just change the '9' to what you want. Changing the '9' to a '7' for example will sort by file size. A '3' sorts by number of links....

Use head and tail at the end of the pipeline to get oldest files or most recent. Use awk or perl -wnla for further processing. Since there is a tab between the two fields, it is very easy to process.

declare -ax CC; for i in `seq 0 7`;do ii=$(($i+7)); CC[$i]="\033[1;3${i}m"; CC[$ii]="\033[0;3${i}m"; done

I was looking for the fastest way to create a bunch of ansi escapes for use in echo -e commands throughout a lot of my shell scripts. This is what I came up with, and I actually stick that loop command in a function and then just call that at the beginning of my scripts to not clutter the environment with these escape codes, which can wreck havok on my terminal when I'm dumping the environment. More of a cool way to store escape ansi codes in an array. You can echo them like:

echo -e "${CC[15]}This text is black on bright green background."

I usually just use with a function:

# setup_colors - Adds colors to array CC for global use # 30 - Black, 31 - Red, 32 - Green, 33 - Yellow, 34 - Blue, 35 - Magenta, 36 - Blue/Green, 37 - White, 30/42 - Black on Green '30\;42' function setup_colors(){ declare -ax CC; for i in `seq 0 7`;do ii=$(($i+7));CC[$i]="\033[1;3${i}m";CC[$ii]="\033[0;3${i}m";done;CC[15]="\033[30;42m"; export R='\033[0;00m';export X="\033[1;37m"; }; export -f setup_colors

CC[15] has a background of bright green which is why it is separate. R resets everything, and X is my default font of bright white.

CC[15]="\033[30;42m"; R=$'\033[0;00m'; X=$'\033[1;37m'

Those are just my favorite colors that I often use in my scripts. You can test which colors by running

for i in $(seq 0 $((${#CC[@]} - 1))); do echo -e "${CC[$i]}[$i]\n$R"; done

See: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html for more usage.

ss -p
2009-09-19 21:55:01
User: Escher

for one line per process:

ss -p | cat

for established sockets only:

ss -p | grep STA

for just process names:

ss -p | cut -f2 -sd\"


ss -p | grep STA | cut -f2 -d\"
seq -s " " -w 3 20
lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +2
(IFS=:;for p in $PATH; do test -d $p || echo $p; done)
2009-09-19 17:51:06
User: haivu
Functions: echo test
Tags: bash PATH

I often need to know of my directory in the PATH, which one DOES NOT exist. This command answers that question

* This command uses only bash's built-in commands

* The parentheses spawn a new sub shell to prevent the modification of the IFS (input field separator) variable in the current shell

netstat -lantp | grep -i stab | awk -F/ '{print $2}' | sort | uniq
2009-09-19 14:54:31
User: ProMole
Functions: awk grep netstat sort

Show apps that use internet connection at the moment.

Can be used to discover what programms create internet traffic. Skip the part after awk to get more details, though it will not work showing only unique processes.

This version will work with other languages such as Spanish and Portuguese, if the word for "ESTABLISHED" still contain the fragment "STAB"(e.g. "ESTABELECIDO")

netstat -lantp | grep -i establ | awk -F/ '{print $2}' | sort | uniq