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 by atoponce from sorted by
Terminal - Commands by atoponce - 53 results
i=$((15*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done;
2010-06-22 17:49:36
User: atoponce
Functions: echo sleep
Tags: figlet timer
1

Requires figlet. Other than that, this should be portable enough across all the Bourne-compatible shells (sh, bash, ksh, zsh, etc).

Produces a massive number using figlet that counts down the number of seconds for any given minute interval. For example, here's a 4-minute timer:

i=$((4*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done;

And a 1-minute timer:

i=$((1*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done;
MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e "\n\nBOOOM! Time to start."
2010-06-20 15:19:12
User: atoponce
Functions: echo seq sleep
Tags: timer counter
10

Simple countdown clock that should be quite portable across any Bourne-compatible shell. I used to teach for a living, and I would run this code when it was time for a break. Usually, I would set "MIN" to 15 for a 15-minute break. The computer would be connected to a projector, so this would be projected on screen, front and center, for all to see.

for code in {000..255}; do print -P -- "$code: %F{$code}Test%f"; done
2010-06-18 22:19:49
User: atoponce
Tags: zsh
2

This will show a numerical value for each of the 256 colors in ZSH. Everything in the command is a ZSH builtin, so it should run on any platform where ZSH is installed. Prints one color per line. If someone is interested in formatting the output, paste the alternative.

dd if=/dev/zero bs=4096 count=1048576 | ssh user@host.tld 'cat > /dev/null'
2010-06-08 18:49:51
User: atoponce
Functions: dd ssh
Tags: ssh dd
5

The above command will send 4GB of data from one host to the next over the network, without consuming any unnecessary disk on either the client nor the host. This is a quick and dirty way to benchmark network speed without wasting any time or disk space.

Of course, change the byte size and count as necessary.

This command also doesn't rely on any extra 3rd party utilities, as dd, ssh, cat, /dev/zero and /dev/null are installed on all major Unix-like operating systems.

lsof -Pan -i tcp -i udp
2010-06-07 15:22:44
User: atoponce
Tags: netstat lsof
25

This command is more portable than it's cousin netstat. It works well on all the BSDs, GNU/Linux, AIX and Mac OS X. You won't find lsof by default on Solaris or HPUX by default, but packages exist around the web for installation, if needed, and the command works as shown. This is the most portable command I can find that lists listening ports and their associated pid.

pkill -USR1 ^dd$
2010-05-14 16:25:01
User: atoponce
Tags: dd kill pkill
3

The 'dd' command doesn't provide a progress when writing data. So, sending the "USR1" signal to the process will spit out its progress as it writes data. This command is superior to others on the site, as it doesn't require you to previously know the PID of the dd command.

cat /path/to/some/file.txt | tee /dev/pts/0 | wc -l
2009-11-07 22:24:28
User: atoponce
Functions: cat tee wc
Tags: tee
2

This is a cool trick to view the contents of the file on /dev/pts/0 (or whatever terminal you're using), and also send the contents of that file to another program by way of an unnamed pipe. All the while, you've not bothered saving any extra data to disk, like you might be tempted to do with sed or grep to filter output.

path+=( /sbin /usr/sbin /usr/local/sbin ); path=( ${(u)path} );
2009-10-31 02:32:25
User: atoponce
Tags: sudo zsh PATH sbin
0

On RHEL, Fedora and CentOS systems, and maybe others, the sbin directories aren't in the user's $PATH. For those systems that use 'sudo', this can be inconvenient typing the full path all the time. As a result, you can easily take advantage of adding the sbin directories to your PATH by adding this simple line to you .zshrc.

sed -r 's/([a-z]+)([A-Z][a-z]+)/\1_\l\2/g' file.txt
2009-04-28 22:44:45
User: atoponce
Functions: sed
11

Useful for switching over someone else's coding style who uses camelCase notation to your style using all lowercase with underscores.

egrep -ci ^[aoeuidhtns-]+$ /usr/share/dict/words
2009-04-15 20:31:46
User: atoponce
Functions: egrep
5

Quick and dirty command that counts how many words can be typed just using the home row on the Dvorak Simplified Keyboard layout from a dictionary file, in this case /usr/share/dict/words.

According to the regular expression supplied, each word must contain all the keys on the Dvorak home row, and no other characters. For comparison, I've shown how many words are installed in my dictionary, how many can be typed with just the Dvorak home row and how many can be typed with just the QWERTY home row in the sample output. Nearly 10 times the amount.

If you want to see the words, remove the -c switch, and each word will be printed out.

dd if=/dev/urandom of=file.img bs=4KB& pid=$!
2009-04-08 05:56:47
User: atoponce
Functions: dd
9

Running this code will execute dd in the background, and you'll grab the process ID with '$!' and assign it to the 'pid' variable. Now, you can watch the progress with the following:

while true; do kill -USR1 $pid && sleep 1 && clear; done

The important thing to grasp here isn't the filename or location of your input or output, or even the block size for that matter, but the fact that you can keep an eye on 'dd' as it's running to see where you are at during its execution.

pinfo date
2009-03-30 10:05:56
User: atoponce
2

The pinfo package makes info pages much more bearable. It is a ncurses-based POSIX utility for viewing info and man pages using lynx style keyboard shortcuts and rendering. Links are highlighted blue, the current location of your cursor is red. Navigating and searching are easy. Worth the install.

< /path/to/file.txt grep foo
2009-03-29 02:43:40
User: atoponce
Functions: grep
15

Several times, I find myself hitting my up arrow, and changing the search term. Unfortunately, I find myself wasting too much time typing:

grep kernel /var/log/messages

Redirecting STDIN allows me to put the search term at the end so I less cursor movement to change what I'm searching for:

< /var/log/messages grep kernel

If you're using the emacs keyboard binding, then after you press your up arrow, press CTRL+w to erase the word.

If this has already been submitted, I couldn't find it with the search utility.

awk '/start_pattern/,/stop_pattern/' file.txt
2009-03-28 14:28:59
User: atoponce
Functions: awk
80

I find this terribly useful for grepping through a file, looking for just a block of text. There's "grep -A # pattern file.txt" to see a specific number of lines following your pattern, but what if you want to see the whole block? Say, the output of "dmidecode" (as root):

dmidecode | awk '/Battery/,/^$/'

Will show me everything following the battery block up to the next block of text. Again, I find this extremely useful when I want to see whole blocks of text based on a pattern, and I don't care to see the rest of the data in output. This could be used against the '/etc/securetty/user' file on Unix to find the block of a specific user. It could be used against VirtualHosts or Directories on Apache to find specific definitions. The scenarios go on for any text formatted in a block fashion. Very handy.

rpm -q --qf "%{VERSION}\n" redhat-release
2009-03-25 16:46:14
User: atoponce
Functions: rpm
2

In this case, I'm getting the package version for 'redhat-release', but of course, this can be applied to any package installed on the filesystem. This is very handy in scripts that need to determine just the version of the package, without the package name and all the sed and grep hackery to get to the data you want. To find out all the support format strings that 'rpm --qf' supports:

rpm --querytags
'ALT+.' or '<ESC> .'
2009-03-20 11:36:04
User: atoponce
256

When typing out long arguments, such as:

cp file.txt /var/www/wp-content/uploads/2009/03/

You can put that argument on your command line by holding down the ALT key and pressing the period '.' or by pressing <ESC> then the period '.'. For example:

cd 'ALT+.'

would put '/var/www/wp-content/uploads/2009/03/ as my argument. Keeping pressing 'ALT+.' to cycle through arguments of your commands starting from most recent to oldest. This can save a ton of typing.

for name in larry moe schemp; do useradd $name; echo 'password' | passwd --stdin $name; chage -d 0 $name; done
2009-03-15 12:02:39
User: atoponce
Functions: chage echo passwd useradd
6

This command is a bit Linux specific, as --stdin doesn't exist for passwd on many Unix machines. Further, useradd is high level in most distributions and Unix derivatives except for the Debian family of distros, where adduser would be more appropriate. The last bit, with chage, will force the user to change their password on new login.

visudo
2009-03-14 03:39:32
User: atoponce
1

'visudo' is installed by default on most Unix-like systems. If not installed, you can get it from the 'sudo' package. 'visudo' will use the text editor found in your $EDITOR variable, whether it's vi, vim, emacs, nano or gedit. After making changes to the /etc/sudoers file, visudo will check for syntax errors, and notify you of them. This is better than 'vi /etc/sudoers', because of this capability. Rule #1 of system administration- if there is a tool that exists for editing config files, use the tool.

rpm2cpio /path/to/file.rpm | cpio -i -d
2009-03-10 21:02:14
User: atoponce
Functions: cpio
1

This assumes you have the 'rpm', 'rpm2cpio' and 'cpio' packages installed. This will extract the contents of the RPM package to your current directory. This is useful for working with the files that the package provides without installing the package on your system. Might be useful to create a temporary directory to hold the packages before running the extraction:

mkdir /tmp/new-package/; cd /tmp/new-package
readom dev=/dev/scd0 f=/path/to/image.iso
2009-03-08 13:21:23
User: atoponce
52

Many like to use 'dd' for creating CD/DVD iso images. This is bad. Very bad. The reason this is, is 'dd' doesn't have any built-in error checking. So, you don't know if you got all the bits or not. As such, it is not the right tool for the job. Instead, 'reaom' (read optical media) from the wodim package is what you should be using. It has built-in error checking. Similarly, if you want to burn your newly creating ISO, stay away from 'dd', and use:

wodim -v -eject /path/to/image.iso
find . -type f -iname '*.wmf' | while read FILE; do FILENAME="${FILE%.*}"; wmf2svg -o ${FILENAME}.svg $FILE; done
2009-03-07 22:21:01
User: atoponce
Functions: find read
3

This assumes you have the package installed necessary for converting WMF files. On my Ubuntu box, this is libwmf-bin. I used this command, as libwmf is not on my wife's iMac, so I archived the directories containing the WMF files from OS X, ran them on my Ubuntu box, archived the resulting SVGs, and sent them back to her. Quick, simple and to the point.

Searches directories recursively looking for extensions ignoring case. This is much more readable and clean than -exec for find. The while loop also gives further flexibility on complex logic. Also, although there is 'wmf2svg --auto', it expects lowercase extensions, and not uppercase. Because I want to ignore case, I need to use the -o option instead.

Works in ZSH and BASH. Haven't tested in other shells.

echo "The date is: $(date +%D)"
2009-03-07 15:51:59
User: atoponce
Functions: echo
76

This is a simple example of using proper command nesting using $() over ``. There are a number of advantages of $() over backticks. First, they can be easily nested without escapes:

program1 $(program2 $(program3 $(program4)))

versus

program1 `program2 \`program3 \`program4\`\``

Second, they're easier to read, then trying to decipher the difference between the backtick and the singlequote: `'. The only drawback $() suffers from is lack of total portability. If your script must be portable to the archaic Bourne shell, or old versions of the C-shell or Korn shell, then backticks are appropriate, otherwise, we should all get into the habit of $(). Your future script maintainers will thank you for producing cleaner code.

sudo find / -type f \( -perm /4000 -a -user root \) -ls -o \( -perm /2000 -a -group root \) -ls
2009-03-02 18:48:17
User: atoponce
Functions: find sudo
2

Discovering all executables on your system that can be run as another user, especially root, is critical for system security. The above command will find those files with have SUID or SGID bits set and are owned by the root user or group.

rm file{1..10}
2009-03-02 14:42:05
User: atoponce
Functions: rm
3

Rather than typing out all 10 files, you can use brace expansion to do the trick for you. This is useful for backup files, numbered files, or any files with a repeating pattern. Gives more control than 'rm file*' as I might want to keep others around.

yum localinstall /path/to/package.rpm
2009-03-02 14:32:23
User: atoponce
6

When downloading RPMs from the Internet, you don't have to 'rpm -i' or 'rpm -U' to install the package. Especially, if the package has dependencies. If you have YUM setup to access an RPM repository, this command will install the downloaded package, then any dependencies through YUM that it relies on. Very handy on RPM-based systems.