20100408

Power to the command line

Are you command-line savvy?

The command line. That small place, where a lot can happen. And more so if you are a Linux user... How to maximize it? Where to harness its power?

I discovered commandlinefu.com a few years ago, while looking for a way to do... something. I don't even enter that often, although it is a brilliant place to discover how to do X in Linux/UNIX.

Among its all time greats I found some gems, and some others I discovered elsewhere, or even I made up.

Command line gems (and rocks?)

Run the last command as root: sudo !! as in
apt-get install something
-> error, you have to be root
sudo !!
The double exclamation mark recovers the last command in the history.

Use the last argument for the last command: !$ as in
mkdir /path/to/somewhere
cd !$
Change to the previous directory: cd - as in (after the previous example to get back to where you started)
cd -
Backward history incremental search: C-r in the terminal prompt, start writing the command you want to backward-search. Press C-r to keep on searching for that term.

Correct typo in previous command: ^typo^corrected as in
sudo apt-get isntall somepackage
^isnt^inst
Write command in editor: C-x C-e will fire the editor in $EDITOR to write the following command.

Open the last modified file of a type: I use this to open the most recent ppm file in a directory with Eye Of Gnome: eog "$(ls -rt *.ppm | tail -n 1)"

Use locate to search for a specific PDF and open it with evince: evince "$(locate *partofname*.pdf)" This will only work if it results in only one instance. If you want to open only the first occurrence evince "$(locate *partofname*.pdf | head -n 1)"

The same with find: evince "$(find -name 'NameOfPdf.pdf')"

Mighty heads and tails: head -n N file, tail -n N file will return the first (resp. last) N lines of file.

Get Pid of a process by name: ps ax | grep "firefox"

Follow changes on a incremental file: tail -f filename as in following nohup.out from a running process.

Get all lines containing a string in a file: grep -e "string" file > outputfile Useful as intermediate step for plotting specific data lines from a nohup.out file. With -r, change the string for a regexp (consider buying this book if you will use them more than once, I recommend it: Mastering Regular Expressions).

I think I have a few more, but I just don't remember them.

What are your special command line tricks?
Are you a command-line jedi or more like a command line young one?

Related posts:
Control your computer by whistling (Linux&Mac)
My first port to the Ben NanoNote: gnugo
sed (stream editor) to colorise script output in Linux
Linux screenshots made easy: Shutter & Screenie
Gcal: the ultra-powerful command line GNU calendar
Written by Ruben Berenguel