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

All commands from sorted by
Terminal - All commands - 11,488 results
(cd /Applications/Firefox.app/Contents/MacOS; ./firefox-bin -p default --no-remote)
watch -n 1 df
2009-02-18 21:34:06
User: joem86
Functions: watch
5

While copying a large file that may take up a good chunk of your hard drive, start the copy and run this command concurrently. It will print out the disk information every second. It's pretty handy when you have a large copy with nothing to monitor the progress.

for i in *; do mv "$i" "$(echo $i|tr A-Z a-z)"; done
2009-02-18 21:29:28
User: mulad
Functions: mv
5

This will convert filenames from uppercase to lowercase. I find this useful after downloading images from my digital camera. This works for English, but other languages may need something slightly more complex like this:

for i in *; do mv "$i" "$(echo $i|tr [:upper:] [:lower:])"; done

Also, the quote marks aren't necessary if your filenames don't contain spaces.

tar -jcvf /folder/file.tar.bz2 --same-owner --same-permissions /folder/
ipconfig /flushdns
ssh user@host 'mysqldump dbname | gzip' > /path/to/backups/db-backup-`date +%Y-%m-%d`.sql.gz
2009-02-18 21:12:53
User: root
Functions: ssh
Tags: mysql
17

I have this on a daily cronjob to backup the commandlinefu.com database from NearlyFreeSpeech.net (awesome hosts by the way) to my local drive. Note that (on my Ubuntu system at least) you need to escape the % signs on the crontab.

ls |while read line ; do mpg321 -w "$line.wav" "$line" ; done
psg() { if [ -z "$2" ]; then psargs="aux"; greparg="$1"; else psargs="$1"; greparg="$2"; fi; ps $psargs | grep -i "$(echo $greparg | sed -e 's/^\(.\)/[\1]/')\|^$(ps $psargs | head -1)" ; }
2009-02-18 20:57:17
User: DEinspanjer
Functions: grep ps
0

My variant on this common function. Some highlights:

Allows you to override the default ps args of "aux"

Uses bracket trick to omit the grep process itself without having to use a second grep

Always prints the correct header row of ps output

Limitations: Ugly ps error output if you forget to quote your multi word grep argument

df -P
2009-02-18 20:53:31
User: AmadeusZull
Functions: df
3

It is a pain grep-ing/sed-ing/awk-ing plain old df. POSIX it!

cp /really/long/path/and/file/name{,-`date -I`}
2009-02-18 20:35:47
User: ozymandias
Functions: cp
4

The expansion {,} in bash will repeat the given string once for each item seperated by commas. The given command will result in the following being run:

cp /really/long/path/and/file/name /really/long/path/and/file/name-`date -I`

These can be embedded as needed, ex: rm file{1,2,3{1,2,3}} would delete the files file1, file2, file31, file32, file32, and no other files.

for (( i = 10; i > 0; i-- )); do echo "$i"; sleep 1; done
2009-02-18 20:31:46
User: mestr
Functions: echo sleep
4

Countdown from 10 or whatever you want:)

trap "echo \"$0 process $$ killed on $(date).\" | tee ${0##*/}_$$_termination.log; echo 'Active processes at the time were logged to ${0##*/}_$$_termination.log'; ps u >> ${0##*/}_$$_termination.log; exit " HUP INT QUIT ABRT TERM STOP
2009-02-18 20:13:29
User: DEinspanjer
Functions: trap
1

trap is the bash builtin that allows you to execute commands when the current script receives a particular signal.

Uses $0 for the script name, $$ for the script PID, tee to output to STDOUT as well as a log file and ps to log other running processes.

TZ=Indian/Maldives date
2009-02-18 20:12:55
User: berta
5

available timezone can be found in /usr/share/zoneinfo. Other examples:

TZ=Europe/Paris date; TZ=Australia/Sydney date; TZ=America/New_York date

this is based on zoneinfo files on macosx. Your mileage my vary on other unix dialects

tar zcpf backup.tgz --exclude=/proc --exclude=backup.tgz /
2009-02-18 19:31:27
User: starchox
Functions: tar
2

You can exclude more system folders or individual files which are not necessary for the backup and can be recreated after the restore procedure, like /lost+found, /mnt, /media, /tmp, /usr ...

Restoring the above backup procedure is as simple as becoming root and typing:

tar zxpf backup.tgz -C /

You can extract any file or directory out of the backup.tgz file for recovery, for instance, if you have a corrupt or mis-configured fstab file, you could simply issue the command:

tar zxpf backup.tgz /ect/fstab -C /

Other options:

v add verbose option to see files processed

A far safer solution is to restore the desired files under a different directory, and then compare, move, or update the files to their original locations afterward.

rm ./-filename
2009-02-18 18:36:25
User: starchox
Functions: rm
5

Using the redundant ./ directory information prevents the dash from occurring at the beginning of the filename, and being interpreted as an option of the rm command.

Also works using:

rm -- -filename
mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "use psa; select accounts.password from accounts INNER JOIN sys_users ON accounts.id=sys_users.account_id WHERE sys_users.login='xxxx';"
2009-02-18 17:26:41
User: darkon1365
0

This will print to the screen password for the user specified in "sys_users.login='xxxx';. This is for Plesk servers only.

''=~('(?{'.('_/@.*@'^'/])@^`').'"'.('"/_/@]/--!.:@</:[@(:/:^'^'[@*]`>@@@@@^`[@_(`@_]_|').',$/})')
vimdiff /path/to/file scp://remotehost//path/to/file
cat /dev/mem > /dev/audio
unset files i; set -f; O=$IFS; while IFS= read -r -d $'\0' files[i++]; do :; done < <(find . -name '*.avi' -print0) && IFS=$O; set +f && echo "Running: mplayer \"${files[ $(( $RANDOM % ${#files[@]} )) ]}\""
2009-02-18 16:53:57
User: DEinspanjer
Functions: echo find read set unset
0

unsets variables used by the one-liner

sets up the IFS bash variable to not be affected by whitespace and disables extra glob expansion

uses read to slurp the results of the find command into an array

selects an element of the array at random to be passed as an argument to mplayer

last | grep -v "^$" | awk '{ print $1 }' | sort -nr | uniq -c
2009-02-18 16:38:59
User: hkyeakley
Functions: awk grep last sort uniq
15

This command takes the output of the 'last' command, removes empty lines, gets just the first field ($USERNAME), sort the $USERNAMES in reverse order and then gives a summary count of unique matches.

perl -pe '$_=reverse;s/\d{3}(?=\d)(?!.*?\.)/$&,/g;$_=reverse'
2009-02-18 16:34:18
User: sil
Functions: perl
2

Insert a comma where necessary when counting large numbers. I needed to separate huge amounts of packets and after 12+ hours of looking in a terminal, I wanted it in readable form.

blockdev --setra 1024 /dev/sdb
2009-02-18 16:27:01
User: starchox
2

(WARN) This will absolutely not work on all systems, unless you're running large, high speed, hardware RAID arrays. For example, systems using Dell PERC 5/i SAS/SATA arrays. If you have a hardware RAID array, try it. It certainly wont hurt.

You may be can test the speed disk with some large file in your system, before and after using this:

time dd if=/tmp/disk.iso of=/dev/null bs=256k

To know the value of block device parameter known as readahead.

blockdev --getra /dev/sdb

And set the a value 1024, 2048, 4096, 8192, and maybe 16384... it really depends on the number of hard disks, their speed, your RAID controller, etc. (see sample)

printf %d 0x`dd if=/dev/urandom bs=1 count=4 2>/dev/null | od -x | awk 'NR==1 {print $2$3}'`
2009-02-18 16:23:09
User: introp
Functions: awk od printf
1

Sometimes, in a shell script, you need a random number bigger than the range of $RANDOM. This will print a random number made of four hex values extracted from /dev/urandom.

svn diff $* | colordiff | less -r
2009-02-18 16:19:08
User: introp
Functions: diff less
2

I put this in a shell script called "svndiff", as it provides a handy decorated "svn diff" output that is colored (which you can't see here) and paged. The -r is required so less doesn't mangle the color codes.