Run the last command as root
$ sudo !!

Serve current directory tree at http://$HOSTNAME:8000/
$ python -m SimpleHTTPServer

Runs previous command but replacing
$ ^foo^bar

Rapidly invoke an editor to write a long, complex, or tricky command
$ ctrl-x e

Place the argument of the most recent command on the shell
$ 'ALT+.' or '<ESC> .'

currently mounted filesystems in nice layout
$ mount | column -t

Salvage a borked terminal
$ reset

Get your external IP address
$ curl ifconfig.me

Execute a command at a given time
$ echo "ls -l" | at midnight

Quick access to the ascii table.
$ man ascii

output your microphone to a remote computer's speaker
$ dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp

type partial command, kill this command, check something you forgot, yank the command, resume typing.
$ <ctrl+u> [...] <ctrl+y>

Query Wikipedia via console over DNS
$ dig +short txt <keyword>.wp.dg.cx

Mount folder/filesystem through SSH
$ sshfs name@server:/path/to/folder /path/to/mount/point

Mount a temporary ram partition
$ mount -t tmpfs tmpfs /mnt -o size=1024m

Download an entire website
$ wget --random-wait -r -p -e robots=off -U mozilla http://www.example.com

Clear the terminal screen
$ ctrl-l

Compare a remote file with a local file
$ ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

SSH connection through host in the middle
$ ssh -t reachable_host ssh unreachable_host

Update twitter via curl
$ curl -u user:pass -d status="Tweeting from the shell" http://twitter.com/statuses/update.xml

A very simple and useful stopwatch
$ time read (ctrl-d to stop)

Put a console clock in top right corner
$ while sleep 1;do tput sc; tput cup 0 $(($( tput cols)-29));date; tput rc;done &

Make 'less' behave like 'tail -f'.
$ less +F somelogfile

Close shell keeping all subprocess running
$ disown -a && exit

Watch Star Wars via telnet
$ telnet towel.blinkenlights.nl

32 bits or 64 bits?
$ getconf LONG_BIT

List of commands you use most often
$ history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head

Simulate typing
$ echo "You can simulate on-screen typing just like in the movies" | pv -qL 10

Set audible alarm when an IP address comes online
$ ping -i 60 -a IP_address

Reboot machine when everything is hanging
$ <alt> + <print screen/sys rq> + <R> - <S> - <E> - <I> - <U> - <B>

quickly rename a file
$ mv filename.{old,new}

Display the top ten running processes - sorted by memory usage
$ ps aux | sort -nk +4 | tail

Delete all files in a folder that don't match a certain file extension
$ rm !(*.foo|*.bar|*.baz)

Push your present working directory to a stack that you can pop later
$ pushd /tmp

Create a script of the last executed command
$ echo "!!" > foo.sh

Watch Network Service Activity in Real-time
$ lsof -i

Easy and fast access to often executed commands that are very long and complex.
$ some_very_long_and_complex_command # label

escape any command aliases
$ \[command]

Show apps that use internet connection at the moment. (Multi-Language)
$ lsof -P -i -n

diff two unsorted files without creating temporary files
$ diff <(sort file1) <(sort file2)

Reuse all parameter of the previous command line
$ !*

Backticks are evil
$ echo "The date is: $( date +%D)"

Sharing file through http 80 port
$ nc -v -l 80 < file.ext

Show File System Hierarchy
$ man hier

Display a block of text with AWK
$ awk '/start_pattern/,/stop_pattern/' file.txt

Set CDPATH to ease navigation
$ CDPATH=:..:~:~/projects

save command output to image
$ ifconfig | convert label:@- ip.png

Add Password Protection to a file your editing in vim.
$ vim -x <FILENAME>

Remove duplicate entries in a file without sorting.
$ awk '!x[$0]++' <file>

Copy your SSH public key on a remote machine for passwordless login - the easy way
$ ssh-copy-id username@hostname

Find Duplicate Files (based on size first, then MD5 hash)
$ find -not -empty -type f -printf "%s
" | sort -rn | uniq -d | xargs -I{} -n1 find -type f -size {}c -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=separate

Kills a process that is locking a file.
$ fuser -k filename

Insert the last command without the last argument (bash)
$ !:-

Python smtp server
$ python -m smtpd -n -c DebuggingServer localhost:1025

Display which distro is installed
$ cat /etc/issue

Find the process you are looking for minus the grepped one
$ ps aux | grep [p]rocess-name

Extract tarball from internet without local saving
$ wget -qO - "http://www. tarball.com/ tarball.gz" | tar zxvf -

Copy your ssh public key to a server from a machine that doesn't have ssh-copy-id
$ cat ~/. ssh/id_rsa.pub | ssh user@machine "mkdir ~/. ssh; cat >> ~/. ssh/authorized_keys"

Matrix Style
$ tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]"

Replace spaces in filenames with underscores
$ rename 'y/ /_/' *

Rip audio from a video file.
$ mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile <output-file> <input-file>

Google Translate
$ translate(){ wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1
/'; }

Inserts the results of an autocompletion in the command line
$ ESC *

Rapidly invoke an editor to write a long, complex, or tricky command
$ fc

A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram
$ sudo dd if=/dev/mem | cat | strings

Graphical tree of sub-directories
$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'

intercept stdout/stderr of another process
$ strace -ff -e trace=write -e write=1,2 -p SOME_PID

Copy a file using pv and watch its progress
$ pv sourcefile > destfile

Define a quick calculator function
$ ? () { echo "$*" | bc -l; }

Create a CD/DVD ISO image from disk.
$ readom dev=/dev/scd0 f=/path/to/image.iso

mkdir & cd into it as single command
$ mkdir /home/foo/doc/bar && cd $_

Create a pdf version of a manpage
$ man -t manpage | ps2pdf - filename.pdf

Stream YouTube URL directly to mplayer.
$ i="8uyxVmdaJ-w";mplayer -fs $(curl -s "http://www.youtube.com/get_video_info?&video_id=$i" | echo -e $(sed 's/%/\\x/g;s/.*\(v[0-9]\.lscache.*\)/http:\/\/\1/g') | grep -oP '^[^|,]*')

Make directory including intermediate directories
$ mkdir -p a/long/directory/path

Easily search running processes (alias).
$ alias 'ps?'='ps ax | grep '

Multiple variable assignments from command output in BASH
$ read day month year <<< $(date +'%d %m %y')

Remove all but one specific file
$ rm -f !(survivior.txt)

git remove files which have been deleted
$ git add -u

Edit a file on a remote host using vim
$ vim scp://username@host//path/to/somefile

Job Control
$ ^Z $bg $disown

Generate a random password 30 characters long
$ s trings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '
'; echo

Show apps that use internet connection at the moment. (Multi-Language)
$ ss -p

Graph # of connections for each hosts.
$ netstat -an | grep ESTABLISHED | awk '{ print $5}' | awk -F: '{ print $1}' | sort | uniq -c | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) { printf("*")}; print "" }'

Record a screencast and convert it to an mpeg
$ ffmpeg -f x11grab -r 25 -s 800x600 -i :0.0 /tmp/outputFile.mpg

Monitor progress of a command
$ pv access.log | gzip > access.log.gz

Search for a <pattern> string inside all files in the current directory
$ grep -RnisI <pattern> *

Monitor the queries being run by MySQL
$ watch -n 1 mysqladmin --user=<user> --password=<password> processlist

Get the 10 biggest files/folders for the current direcotry
$ du -s * | sort -n | tail

Show numerical values for each of the 256 colors in bash
$ for code in {0..255}; do echo -e "\e[38;05;${ code}m $ code: Test"; done

Recursively remove all empty directories
$ find . -type d -empty -delete

Display a cool clock on your terminal
$ watch -t -n1 "date +%T|figlet"

Convert seconds to human-readable format
$ date -d@1234567890

Nice weather forecast on your shell
$ curl wttr.in/seville

Check your unread Gmail from the command line
$ curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '
' | awk -F '<en try>' '{for (i=2; i<=NF; i++) {print $i}}' | sed -n "s/<title>\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 - \1/p"

Search commandlinefu.com from the command line using the API
$ cmdfu(){ curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; }

Processor / memory bandwidthd? in GB/s
$ dd if=/dev/zero of=/dev/null bs=1M count=32768

pretend to be busy in office to enjoy a cup of coffee
$ cat /dev/urandom | hexdump -C | grep "ca fe"

Makes the permissions of file2 the same as file1
$ chmod --reference file1 file2

Remove security limitations from PDF documents using ghostscript
$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=OUTPUT.pdf -c .setpdfwrite -f INPUT.pdf

Send pop-up notifications on Gnome
$ notify-send ["<title>"] "<body>"

(Debian/Ubuntu) Discover what package a file belongs to
$ dpkg -S /usr/bin/ls

Mount a .iso file in UNIX/Linux
$ mount /path/to/file.iso /mnt/cdrom -oloop

Remove a line in a text file. Useful to fix
$ ssh-keygen -R <the_offending_host>

To print a specific line from a file
$ sed -n 5p <file>

Open Finder from the current Terminal location
$ open .

Create a persistent connection to a machine
$ ssh -MNf <user>@<host>

Run a command only when load average is below a certain threshold
$ echo "rm -rf /unwanted-but-large/folder" | batch

Create a quick back-up copy of a file
$ cp file.txt{,.bak}

Start COMMAND, and kill it if still running after 5 seconds
$ timeout 5s COMMAND

Attach screen over ssh
$ ssh -t remote_host screen -r

Show a 4-way scrollable process tree with full details.
$ ps awwfux | less -S

List all bash shortcuts
$ bind -P

RTFM function
$ rtfm() { help $@ || man $@ || $BROWSER "http://www.google.com/search?q=$@"; }

Eavesdrop on your system
$ diff <( lsof -p 1234) <(sleep 10; lsof -p 1234)

Remove all files previously extracted from a tar(.gz) file.
$ tar -tf <file. tar.gz> | xargs rm -r

Broadcast your shell thru ports 5000, 5001, 5002 ...
$ script -qf | tee >(nc -kl 5000) >(nc -kl 5001) >(nc -kl 5002)

Directly ssh to host B that is only accessible through host A
$ ssh -t hostA ssh hostB

which program is this port belongs to ?
$ lsof -i tcp:80

What is my public IP-address?
$ curl ifconfig.me

Retry the previous command until it exits successfully
$ until !!; do :; done

Synchronize date and time with a server over ssh
$ date --set="$(ssh user@server date)"

Edit a google doc with vim
$ google docs edit --title "To-Do List" -- editor vim

Run a file system check on your next boot.
$ sudo touch /forcefsck

List only the directories
$ ls -d */

Share a terminal screen with others
$ % screen -r someuser/

Google text-to-speech in mp3 format
$ wget -q -U Mozilla -O output.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=hello+world

Download all images from a site
$ wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" http://example.com/images

Download Youtube video with wget!
$ wget http://www.youtube.com/watch?v=dQw4w9WgXcQ -qO- | sed -n "/fmt_url_map/{s/[\'\"\|]/
/g;p}" | sed -n '/^fmt_url_map/,/videoplayback/p' | sed -e :a -e '$q;N;5,$D;ba' | tr -d '
' | sed -e 's/\(.*\),\(.\)\{1,3\}/\1/' | wget -i - -O surprise.flv

Python version 3: Serve current directory tree at http://$HOSTNAME:8000/
$ python -m http.server

Get your outgoing IP address
$ dig +short myip.opendns.com @resolver1.opendns.com

Binary Clock
$ watch -n 1 'echo "obase=2;`date +%s`" | bc'

Sort the size usage of a directory tree by gigabytes, kilobytes, megabytes, then bytes.
$ du -b --max-depth 1 | sort -nr | perl -pe 's{([0-9]+)}{sprintf "%.1f%s", $1>=2**30? ($1/2**30, "G"): $1>=2**20? ($1/2**20, "M"): $1>=2**10? ($1/2**10, "K"): ($1, "")}e'

Duplicate installed packages from one machine to the other (RPM-based systems)
$ ssh root@remote.host "rpm -qa" | xargs yum -y install

Draw kernel module dependancy graph.
$ lsmod | perl -e ' print "digraph \" lsmod\" {";<>;while(<>){@_=split/\s+/; print "\"$_[0]\" -> \"$_\"
" for split/,/,$_[3]} print "}"' | dot -Tpng | display -

Compare two directory trees.
$ diff <(cd dir1 && find | sort) <(cd dir2 && find | sort)

Bring the word under the cursor on the :ex line in Vim
$ :<C-R><C-W>

Remind yourself to leave in 15 minutes
$ leave +15

make directory tree
$ mkdir -p work/{d1,d2}/{src,bin,bak}

Convert Youtube videos to MP3
$ youtube-dl -t --extract-audio --audio-format mp3 YOUTUBE_URL_HERE

Find out how much data is waiting to be written to disk
$ grep ^Dirty /proc/meminfo

Use tee to process a pipe with two or more processes
$ echo "tee can split a pipe in two"|tee >(rev) >(tr ' ' '_')

Show apps that use internet connection at the moment.
$ lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +2

Backup all MySQL Databases to individual files
$ for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done

Port Knocking!
$ knock <host> 3000 4000 5000 && ssh -p <port> user@host && knock <host> 5000 4000 3000

Add timestamp to history
$ export HISTTIMEFORMAT="%F %T "

Recursively change permissions on files, leave directories alone.
$ find ./ -type f -exec chmod 644 {} \;

Find files that have been modified on your system in the past 60 minutes
$ sudo find / -mmin 60 -type f

Quick access to ASCII code of a key
$ showkey -a

Using `!#$' to referance backward-word
$ cp /work/host/phone/ui/main. cpp !#$:s/host/target

Search recursively to find a word or phrase in certain file types, such as C code
$ find . -name "*.[ch]" -exec grep -i -H "search pharse" {} \;

Intercept, monitor and manipulate a TCP connection.
$ mkfifo /tmp/fifo; cat /tmp/fifo | nc -l -p 1234 | tee -a to.log | nc machine port | tee -a from.log > /tmp/fifo

Block known dirty hosts from reaching your machine
$ wget -qO - http://infiltrated.net/blacklisted|awk '!/#|[a-z]/&&/./{print "iptables -A INPUT -s "$1" -j DROP"}'

Check site ssl certificate dates
$ echo | openssl s_client -connect www.google.com:443 2>/dev/null | openssl x509 -dates -noout

Find files in a date range
$ find . -type f -newermt "2010-01-01" ! -newermt "2010-06-01"

Control ssh connection
$ [enter]~?

Run complex remote shell cmds over ssh, without escaping quotes
$ ssh host -l user $(<cmd.txt)

Create a directory and change into it at the same time
$ md () { mkdir -p "$@" && cd "$@"; }

Colorized grep in less
$ grep --color=always | less -R

Exclude multiple columns using AWK
$ awk '{$1=$3=""}1' file

ls not pattern
$ ls !(*.gz)

output your microphone to a remote computer's speaker
$ arecord -f dat | ssh -C user@host aplay -f dat

analyze traffic remotely over ssh w/ wireshark
$ ssh root@server.com 'tshark -f "port !22" -w -' | wireshark -k -i -

Given a file path, unplug the USB device on which the file is located (the file must be on an USB device !)
$ echo $( sudo lshw -businfo | grep -B 1 -m 1 $(df "/path/to/file" | tail -1 | awk '{print $1}' | cut -c 6-8) | head -n 1 | awk '{print $1}' | cut -c 5- | tr ":" "-") | sudo tee /sys/bus/usb/drivers/usb/unbind

Remove a line in a text file. Useful to fix "ssh host key change" warnings
$ sed -i 8d ~/.ssh/known_hosts

Save a file you edited in vim without the needed permissions (no echo)
$ :w !sudo tee > /dev/null %

Remove blank lines from a file using grep and save output to new file
$ grep . filename > newfilename

delete a line from your shell history
$ history -d

Get the IP of the host your coming from when logged in remotely
$ echo ${SSH_CLIENT%% *}

Random Number Between 1 And X
$ echo $[RANDOM%X+1]

Lists all listening ports together with the PID of the associated process
$ lsof -Pan -i tcp -i udp

easily find megabyte eating files or directories
$ alias dush="du -sm *|sort -n|tail"

Exclude .svn, .git and other VCS junk for a pristine tarball
$ tar --exclude-vcs -cf src. tar src/

exit without saving history
$ kill -9 $$

How to establish a remote Gnu screen session that you can re-connect to
$ ssh -t user@some.domain.com /usr/bin/screen -xRR

Copy a MySQL Database to a new Server via SSH with one command
$ mysqldump --add-drop-table --extended-insert --force --log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost "mysql -uUSER -pPASS NEW_DB_NAME"

Convert PDF to JPG
$ for file in `ls *.pdf`; do convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 $ file `echo $ file | sed 's/\.pdf$/\.jpg/'`; done

Find usb device
$ diff <(lsusb) <(sleep 3s && lsusb)

find all file larger than 500M
$ find / -type f -size +500M

notify yourself when a long-running command which has ALREADY STARTED is finished
$ <ctrl+z> fg; notify_me

Create colorized html file from Vim or Vimdiff
$ :TOhtml

live ssh network throughput test
$ yes | pv | ssh $host "cat > /dev/null"

Create a nifty overview of the hardware in your computer
$ lshw -html > hardware.html

Save your sessions in vim to resume later
$ :mksession! <filename>

Tell local Debian machine to install packages used by remote Debian machine
$ ssh remotehost ' dpkg --get-selections' | dpkg --set-selections && dselect install

Bind a key with a command
$ bind -x '"\C-l":ls -l'

Take screenshot through SSH
$ DISPLAY=:0.0 import -window root /tmp/shot.png

intersection between two files
$ grep -Fx -f file1 file2

GREP a PDF file.
$ pdftotext [file] - | grep 'YourPattern'

Colorful man
$ apt-get install most && update-alternatives --set pager /usr/bin/ most

copy working directory and compress it on-the-fly while showing progress
$ tar -cf - . | pv -s $(du -sb . | awk '{print $1}') | gzip > out.tgz

prints line numbers
$ nl

convert unixtime to human-readable
$ date -d @1234567890

A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram
$ sudo strings /dev/mem

Diff on two variables
$ diff <(echo "$a") <(echo "$b")

Prettify an XML file
$ tidy -xml -i -m [file]

Encrypted archive with openssl and tar
$ tar --create --file - --posix --gzip -- <dir> | openssl enc -e -aes256 -out <file>

Convert seconds into minutes and seconds
$ bc <<< 'obase=60;299'

Alias HEAD for automatic smart output
$ alias head='head -n $((${LINES:-`tput lines 2>/dev/null||echo -n 12`} - 2))'

Pipe stdout and stderr, etc., to separate commands
$ some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr)

Manually Pause/Unpause Firefox Process with POSIX-Signals
$ killall -STOP -m firefox

Gets a random Futurama quote from /.
$ curl -Is slashdot.org | egrep '^X-(F|B|L)' | cut -d \- -f 2

Use lynx to run repeating website actions
$ lynx -accept_all_cookies -cmd_script=/your/keystroke-file

runs a bash script in debugging mode
$ bash -x ./post_to_commandlinefu.sh

Instead of writing a multiline if/then/else/fi construct you can do that by one line
$ [[ test_condition ]] && if_true_do_this || otherwise_do_that

Display a list of committers sorted by the frequency of commits
$ svn log -q|grep "|"|awk "{print \$3}"|sort|uniq -c|sort -nr