Some useful shell tricks for you

Bind a key to a command in Bash

You can bind, for example, the command ls -l to CTRL+l using:

bind -x '"\C-l":"ls -l\n"'

It may be useful to append this line in your .bashrc. Now, every time you press CTRL+l, even in the middle of another command, a directory listing will appear!

Run the last command as root

sudo !!

We all know what the sudo command does - it runs the command given as argument as another user. If no other user is specified, it runs the command given as argument as superuser. But what's really interesting is the bang-bang !! part of the command. It's called the event designator. An event designator references a command in shell's history. In this case the event designator references the previous command. Writing !! is the same as writing !-1. The -1 refers to the last command. You can generalize it, and write !-n to refer to the n-th previous command. To view all your previous commands, type history.

Serve the current directory as a web server

python -m SimpleHTTPServer <PORT>

Replace <PORT> with the desiderd port. If none specified, the default is 8000. One of the many reasons *nix is wonderful: you can have everything, as simple as it gets.

This one-liner starts a web server on a desired port with the contents of current directory on all the interfaces (address 0.0.0.0), not just localhost. If you have "index.html" or "index.htm" files, it will serve those, otherwise it will list the contents of the currently working directory. It works using Python standard module SimpleHTTPServer. The -m argument makes python to search for a module named SimpleHTTPServer.py in all the possible system locations (listed in sys.path and $PYTHONPATH shell variable). Once found, it executes it as a script.

Start an SMTP server

python -m smtpd -n -c DebuggingServer localhost:<PORT>

This one-liner starts an SMTP server on a chosen port > 1024 (only root can listen to ports <= 1024).

Change to the previous working directory

cd -

Quickly backup or copy a file

cp filename{,.bak}

This one-liner copies the file named filename to a file named filename.bak. Here is how it works. It uses brace expansion to construct a list of arguments for the cp command. Brace expansion is a mechanism by which arbitrary strings may be generated. In this one-liner filename{,.bak} gets brace expanded to filename filename.bak and puts in place of the brace expression. The command becomes cp filename filename.bak and the file gets copied.

Brace expansion

Talking more about brace expansion, you can do all kinds of combinatorics with it. Here is a fun application:

echo {a,b,c}{a,b,c}{a,b,c}

It generates all the possible 3-letter strings from the set {a, b, c}:

aaa aab aac aba abb abc aca acb acc
baa bab bac bba bbb bbc bca bcb bcc
caa cab cac cba cbb cbc cca ccb ccc

And here is how to generate all the possible 2-letter strings from the set {a, b, c}:

echo {a,b,c}{a,b,c}

Output:

aa ab ac ba bb bc ca cb cc

Capture screen as a video with ffmpeg

ffmpeg -f x11grab -s 800x600 -r 25 -i :0.0 -sameq /tmp/capture.mpg

Quick options overview (see man ffmpeg [good luck!] for more info): -f x11grab makes ffmpeg to set the input video format as x11grab. It is OK for X11 framebuffer. -s 800x600 makes ffmpeg set the size of the video to 800x600. Feel free to try other resolutions! :) -r 25 sets the framerate of the video to 25fps. -i :0.0 sets the video input file to X11 display 0.0 at localhost. -sameq preserves the quality of input stream. It's best to preserve the quality and post-process it later.

Wipe a file

> file.txt

This command either wipes the file file.txt or creates a new file called file.txt.

Tweet from the shell using curl

curl -u user:pass -d status='Tweeting from Bash!' http://twitter.com/statuses/update.xml

This one-liner tweets your message from the terminal. It uses the curl program to HTTP POST your tweet via Twitter's API.

Find out which programs listen on which TCP ports

netstat -tlnp

Paramaters overview: -t causes netstat to only list information about TCP sockets. -l causes netstat to only list listening sockets. -n disables reverse lookups on the IPs. -p causes netstat to print the PID and name of the program to which the socket belongs.

Display currently mounted file systems formatted in columns

nicemount() { (echo "DEVICE PATH TYPE FLAGS" && mount | awk '$2=$4="";1') | column -t; }

You can add the alias definition on your .bashrc, so that you can call nicemount every time you need it, directly.

Read Wikipedia via DNS

dig +short txt <keyword>.wp.dg.cx

David Leadbeater created a DNS server, which when queried with a TXT record type, returns a short plain-text version of a Wikipedia article. Here is his presentation. This allows us to query Wikipedia even behind a restrictive firewall which blocks TCP requests, but not DNS queries (i.e. WiFi in hotels).

Download a website recursively with wget

wget --random-wait -r -l 10 -p -e robots=off -U Mozilla www.example.com

Here is the explanation of the arguments:

--random-wait - wait between 0.5s to 1.5s between requests. -r - recursive retrieving. -e robots=off - ignore robots.txt. -U Mozilla - fake the UserAgent. -l 10 - recursion depth limit, set it to -l 0 for unlimited.

Show the size of all sub folders in the current directory

du -h --max-depth=1

If you are interested in both subfolder size and file size in the current directory, you can use the shorter:

du -sh *

Display the top ten running processes sorted by memory usage

ps aux | sort -nk +4 | tail

Quickly access ASCII table

man ascii

A simple timer

time read

This one-liner can be used as a simple timer. For example, if you wish to time something, you can execute it when the event starts and press the return key when it ends. It will output how much time has passed between the instant you fired it up and the instant you pressed return.

List 10 most often used commands

history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head

First, history outputs all the commands the person has executed. Next, awk counts how many times the second column $2 appears in the output. Once history has output all the commands and awk has counted them, awk loops over all the commands and outputs the count a[i] separated by space, followed by the command itself. Then sort takes this input and sorts numerically -n and reverses the output -r, so that most frequent commands were on top. Finally head outputs the first 10 most frequent history commands.