Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Share your command line features and tricks for Unix/Linux. Try to keep it shell/distro agnostic if possible. Interested in seeing aliases, one-liners, keyboard shortcuts, small shell scripts, etc.


locked by Michael Mrozek Nov 6 '11 at 0:41

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

63 Answers 63

This expands somewhat on the !! trick mentioned in this answer. There are actually a bunch of history-related commands that tend to get forgotten about (people tend to stab Up 100 times instead looking for a command they know they typed).

  • The history command will show a list of recently run commands with an event designator to the left
  • !N will substitute the command associated with event designator N
  • !-N will substitute the N th most recent command; e.g. !-1 will substitute the most recent command, !-2 the second most recent, etc.
  • As mentioned in the other answer, !! is shorthand for !-1, to quickly substitute the last command
  • !string will substitute the most recent command that begins with string
  • !?string? will substitute the most recent command that contains string

Word designators can be added on to a ! history command to modify the results. A colon separates the event and word designators, e.g. !!:0. The event designator !! can be abbreviated to just ! when using a word designator, so !!:0 is equivalent to !:0.

  • !:0 will get the command that was executed
  • !:1 will get the first argument (and !:2 the second, etc.)
  • !:2-3 will get the second and third arguments
  • !:^ is another way to get the first argument. !:$ will get the last
  • !:* will get all arguments (but not the command)

Modifiers can also be appended to a ! history command, each prefixed by a colon. Any number can be stacked on (e.g. !:t:r:p).

  • h -- Line up to the base filename
  • t -- Only the base filename
  • r -- Line up to the filename extension
  • e -- Only the filename extension
  • s/search/replacement -- Replace the first occurrence of search with replacement
  • gs/search/replacement -- Replace all occurrences of search with replacement
You, sir, are a command-line God. Even I (as if that matters ;-)) didn't know about the !:h stuff :-) – wzzrd Aug 12 '10 at 14:14
And if you're using Bash (could be the same for certain other shells), M-^ (Meta-^) expands the above history expansion operators for you, just in case you'd like to see what you're actually referring to. – Eric Smith Sep 16 '10 at 14:41
I've never found a use for the ! command things. It just seems bad to me to run a command that I'm not seeing. It'd be so easy to type !-3 instead of !-4, and who knows what could happen. Finding the line number of the command I want to run is usually more a pain than it's worth. Cool tricks though, but I've never found a real use for them. – Falmarri Dec 16 '10 at 18:37
@Falmarri I never use the !-# ones either. I do use !string to run the last command that starts with string, but I generally tab-complete it first (zsh) to make sure I'm running the right thing – Michael Mrozek Dec 16 '10 at 18:42
No! :) "Running !N will run the command ..." is a description too narrow; actually, !N will be substituted by the command ... ; and so on for all the descriptions in the answer. More correct and opening much more useful possibilities! E.g., the mentioned sudo !!. – imz -- Ivan Zakharyaschev Mar 16 '11 at 1:34

bash -- insert preceding line's final parameter

alt-. the most useful key combination ever, try it and see, for some reason no one knows about this one.

press it again and again to select older last parameters.

great when you want to do something more to the argument/file you used just a moment ago.

You can also use !$ to refer to the last arg in the previous command. This is useful because it works in scripts as well as interactively. (Works in bash & zsh) – Jerry H. Aug 10 '10 at 20:07
Each time you hit alt-. it will go to the previous command and pull the last argument from it. So if you want the last argument from three commands ago, just hit alt-. three times. – clee Aug 20 '10 at 20:09
This is the default key binding for the yank-last-arg readline command, so it should work with any program linked against readline, not just BASH or ZSH. – James Sneeringer Oct 5 '11 at 16:58
In vi mode, I had to rebind yank-last-arg as per this answer: superuser.com/questions/18498/… – Jeromy Anglim Oct 8 '11 at 13:14
In xterm, meta-. produces ®, but you can use esc instead of meta (in general in bash), so esc-. instead. – derobert Nov 11 '11 at 22:01

My favorite is

man 7 ascii

Simple and so very useful.

alt text

Have a look at this website commandlinefu.com.

You can also have a look at these four articles by Peteris Krumins on his blog

The separate ascii program is also useful. Besides printing a table, it lets you query for one or more individual characters. – Matthew Flaschen Aug 15 '10 at 5:24

Execute last command as root:

sudo !!
This is useful! Oftentimes you don't know if the permission allows, and if it doesn't, sudo !! is probably faster than <Up><C-A>sudo <CR>. – progo Mar 15 '11 at 10:55

Not sure if this counts as a "trick", but people seem very unaware of the standard readline hotkeys. Of particular use in shells:

  • Ctrl+U - Cut the current line
  • Ctrl+Y - Paste a line cut with Ctrl+U
  • Ctrl+L - Clear the screen and redraw the current line
  • Ctrl+G - Get a new line and abandon the current one
thanks a lot for Ctrl+L, I have always used 'clear' – phunehehe Aug 11 '10 at 7:08
Just to add a few to these: Ctrl+A to go to the beginning of the line, Ctrl+E to go to the end of the line, Ctrl-K to erase from the cursor to the end of the line. – rsuarez Jan 24 '11 at 15:13
Ctrl+L corresponds to the FormFeed ascii character. It will typically redraw the screen in text applications with a screen window (e.g. vim, less, mc, etc). Nice if the screen has been "polluted" by some output from another program. – hlovdal Mar 17 '11 at 22:13
Adding to the list of hot-keys: Ctrl+W to cut one word backwards, Alt+F to go forward one word, Alt+B to go one word backward in a line. I like Ctrl+Y and Shift+Insert because you can have two copied lines. One with Ctrl+U ( paste it with Ctrl+Y ) and at the same time you can copy another word ( select the line ) paste with (Shift+Insert). – user14039 Feb 24 '12 at 19:26

CTRL+R in BASH for searching/activating previously executed commands (the contents of ~/.bash_history).

This is often extremely helpful. Running this alias will serve the PWD up over HTTP (indexed) on port 8000:

alias webserver="python -m SimpleHTTPServer"

And because I run make all the time, and spaz out and type too quickly, these aliases are probably my most used (seriously):

alias maek=make
alias mkae=make
alias meak=make
alias amka=make
alias akme=make

And probably my most frequently used piece of BASH is a simple script I call upload. I use it to blit any kind of content to my Linode, and it copies the resulting HTTP URL to my clipboard (middle click). Very useful for pasting stuff to people in IRC:

scp -r $* $user@$host:public_html && {
    URL="http://$host/~$user/$(basename $1)"
    echo "$URL"
    xselection -replace PRIMARY "$URL"

Just a couple. I can post much more later, must get back to work!

alias mk=make Faster to type and less likely to get wrong. Or compile from your editor using a hotkey... – Lars Haugseth Aug 13 '10 at 5:29
BTW Zsh has built-in spelling correction that is very good at correcting simple typos. – Adam Byrtek Sep 15 '10 at 17:14
Also in zsh, I think the default is when you hit the up key it does a history search as if you had hit ctrl r. Might not be the default, but it's a setting. – Falmarri Dec 16 '10 at 18:40
I'd consider alias m=make, or even m=make -j6 or similar -- except I already use alias m=mutt – jmtd May 10 '11 at 12:54

diff the output of two commands without creating a temporary file manually (bash):

diff <(ls dir1) <(ls dir2)
Very nice. Thanks for this one. – Sergio Acosta Aug 26 '10 at 9:08
This is also super useful for comm as it takes files only, but in a lot of cases that's a waste of inodes. – Marcin May 5 '11 at 14:11

Pretty basic, but people don't seem to know, returns you to the previous dir:

cd -
I tell you, cd.. from DOS is ingrained in my muscle memory... – LawrenceC Feb 16 '11 at 5:04
This is a cheap version of pushd and popd though... – Robert Massaioli Feb 17 '11 at 21:30
Similarly, there is cd (with no argument) which takes you to your home directory. – Mei Feb 3 '12 at 23:57
Yeah, that's crazy. Where in the man page does it show the expansion of '-'? I'm always trying (and forgetting) to use pushd/popd – Chuck R Feb 20 '12 at 22:02

Brace Expansion:

Brace expansion is a mechanism by which arbitrary strings may be generated.

It allows you to replace tedious lines like:

mv loong/and/complex/file/name loong/and/complex/file/name.bacukup

with a shorter instance

mv loong/and/complex/file/name{,backup}

some other uses

# to display the diff between /etc/rc.conf and /etc/rc.conf.pacsave
diff /etc/rc.conf{,.pacsave}

# to list files in both /usr/share and /usr/local/share
ls /usr/{,local}/share 

Arithmetic Expansion:

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:


The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic expansions may be nested.

$ a=1
$ b=2
$ echo $(( a+(b*2) ))
Nice, I can't believe I forgot about this. There's also a more compact foo[123] that will expand into foo1 foo2 foo3, but they need to be filenames to work in that case – Michael Mrozek Sep 23 '10 at 14:31
hehe.. thanks... learn something everyday +1 – Stefan Sep 29 '10 at 20:19

This is usually in my startup script (.bashrc, .profile, whatever)

shopt goodness, check the comments:

shopt -s cdspell        # try to correct typos in path
shopt -s dotglob        # include dotfiles in path expansion
shopt -s hostcomplete   # try to autocomplete hostnames

An alias that save keystrokes: mkdir and cd into it:

mkcd () { mkdir -p "$@" && cd "$@"; }

And last but not least, I've given up on memorizing tar syntax, so:

extract () {
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)  tar xjf $1      ;;
            *.tar.gz)   tar xzf $1      ;;
            *.bz2)      bunzip2 $1      ;;
            *.rar)      rar x $1        ;;
            *.gz)       gunzip $1       ;;
            *.tar)      tar xf $1       ;;
            *.tbz2)     tar xjf $1      ;;
            *.tgz)      tar xzf $1      ;;
            *.zip)      unzip $1        ;;
            *.Z)        uncompress $1   ;;
            *)          echo "'$1' cannot be extracted via extract()" ;;
        echo "'$1' is not a valid file"
+1, why didn't I think of that? (extract) – MAK Sep 19 '10 at 16:48
I have a similar function to mkcd only that I name id md. However the using "$@" as argument to cd does not make any sense since you cannot cd to more than one single directory. "$@" will work for mkdir, but then you are handling arguments differently for mkdir and cd, so I would rather suggest md () { mkdir -p "$1"; cd "$1" } – hlovdal Mar 17 '11 at 22:20
how do I add those commands? just paste as is to .bashrc or add "alias" before them? – Asaf Nov 18 '11 at 19:34

Two bash functions which save me many key strokes.

Do automatically an ls after every successfull cd:

function cd {
    builtin cd "$@" && ls

Go up n levels:

# Usage .. [n]
function .. (){
    local arg=${1:-1};
    local dir=""
    while [ $arg -gt 0 ]; do
        arg=$(($arg - 1));
    cd $dir #>&/dev/null
I never realized you could do builtin foo to get around having a function defined cd; I've been using chdir in my functions. Handy – Michael Mrozek Aug 11 '10 at 13:39
Awesome. Just add -F to ls in the cd function and it's perfect (for me)! – frabjous Aug 22 '10 at 2:49
I do the same as you for cd, but I have a few more sanity checks in and avoid doing ls in non-interactive mode: cd() { builtin cd -- "$@" && { [ "$PS1" = "" ] || ls -hrt --color; }; } – jmtd May 10 '11 at 14:27

Since I'm usually halfway into a command line before wanting to search (CTRL-R in bash) I have the following in my .bashrc

bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward

This means that if I type cd then press up/down I can see all the options that I have cd'd to. Basically I use this for often used dirs. Like "cd w" and I'm ending up going through all the workspaces I use lots.

This one is really great ! It extends the arrows behaviour without breaking their basic functionality.Thanks ! – philfr Mar 16 '11 at 8:41

One thing that saves me a lot of time is the pushd/popd commands. These guys let you create a stack of directories and reduce typing a lot:

/foobar/ > pushd /src/whatever/foo/test
/foobar/src/whatever/foo/test > make run
/foobar/src/whatever/foo/test > popd
/foobar/ > make
Yes! alias u=pushd; alias o=popd – cannedprimates Aug 15 '10 at 9:57
.. and what do u and o stand for here? – deizel Aug 19 '10 at 11:32
@deizel: Nothing specific, just a shortcut to avoid typing. – Adam Byrtek Sep 15 '10 at 17:15
Looks like the second letter of the command, since they both start with p, you can't use that for both. – camh Sep 16 '10 at 10:20
In ZSH you can setopt autopushd and all directory changes will push automatically – Michael Mrozek Sep 23 '10 at 14:34

The screen command. It basically saves your command line session for when you come back. It's sort of a terminal manager, like a window manager. That way, in a single terminal session, you can have multiple virtual terminals going on. It's very cool.

If one uses screen, this shell function (put it into .bashrc) is extremely useful:

function scr {
    if screen -ls | grep -q Main; then
         # reattach to Main: 
         screen -xr Main
         # name session "Main":
         screen -S Main

upon typing scr, it will check if your main session exists and will attach to it. Otherwise it will create it.

technically, it is a program of its own, not a "command". – progo Mar 15 '11 at 11:00
I'd recommend tmux or dvtm over screen. They are more modern and cleaner replacements. – deltaray Nov 20 '11 at 3:59
Yes, "tmux" is unarguably much better than screen. – ColinM Mar 2 '12 at 21:38
It also more closely follows the unix convention of unintuitive, abbreviated names :) – user394 Mar 5 '12 at 15:00

If you need to edit a particularly long command line in bash

^X^E (Ctrl-X Ctrl-E) 

will open it in the editor ($EDITOR).

In zsh you can get the same behaviour by adding this to .zshrc:

autoload edit-command-line
zle -N edit-command-line
bindkey '^X^e' edit-command-line 
Wow, that one goes into The Book. – l0b0 Jun 20 '11 at 13:29
Yeah, and into my notes! – jyz Jul 1 '11 at 0:28

If you are a fast typist, these come in handy:

alias grpe='grep --color=tty'
alias gpre='grep --color=tty'
alias rgep='grep --color=tty'
alias gerp='grep --color=tty'

This macro helps you compute totals of a column of output: file sizes, bytes, packets, all you have to do is specify the column that you want to add:

total ()
        if [ x$1 = x ]; then set `echo 1`; fi
        awk "{total += \$$1} END {print total}"

You use it like this for example, with no arguments, it adds the total of the first column:

du | total

If you provide the argument, it will sum that column, for example, this gives you the total number of bytes used by all the C# files in /tmp:

ls -l /tmp/*cs | total 5

Sometimes your console gets messed up because you accidentally viewed a binary file (cat /bin/ls for example), you can restore the terminal with this shell function:

restaura ()
    perl -e 'print "\e)B";'

I like my ls to use characters to distinguish the class of files, and also to hide the backup files generated by my editor (backup files end with the ~ character):

alias ls='ls -FB'
Don't forget: alias gerp='grep --color=tty' I do that one all the time ;-) – Swish Aug 24 '10 at 22:19
Far as I'm concerned, "fast" doesn't count if I'm not accurate. You may also want to look at the GREP_COLORS and GREP_OPTIONS variables. – Andy Lester Oct 8 '10 at 22:58
s/fast/sloppy/ – Josh Dec 14 '10 at 16:00
I use reset where you use restaura. – jmtd May 10 '11 at 13:04
alias s='sudo'
alias r='rake' # i'm a ruby developer
alias ..='cd ..' # although with autocd feature for zsh this comes packed.

One of my favorites when I forget s:

$ s !! # last command with super user priviledges
If you use ZSH you can do something like bindkey -s '\e[12~' "sudo !!\n" to bind (in this case) F2 to run that command. I have that binding, so when I run something and see the "you forgot 'sudo', fool" error message, I can just stab at F2 in annoyance – Michael Mrozek Aug 10 '10 at 19:50
Poor F2 key... .) – Eimantas Aug 10 '10 at 19:55
I use this all the time. I constantly forget to type sudo before editing my hosts file. If that happens I just run sudo !!. +1 – Brian Wigginton Jan 13 '11 at 22:16

If a command takes stdin input, you can read the input from a file with <filename. This can appear anywhere in the command, so these lines are equivalent:

cat filename
cat <filename
<filename cat

This is particularly useful for grep, as it allows you to place the expression at the end of the line, so you can quickly modify a grep command it by hitting Up, without needing to scroll left to get past the filename:

<filename grep 'expression'
A good tip! Worth noting that this doesn't actually reorder the arguments to the command. Instead it pipes the file into the process' STDIN, as grep now has no file argument it defaults to reading from STDIN. Understanding this will open many opportunities to use this technique with other commands and also help people to understand what's going on when things don't work as expected. For more info look up pipes and redirectors: dsj.net/compedge/shellbasics1.html – chillitom Aug 10 '10 at 20:23
@chill Good points; the tip was actually phrased so poorly as to be essentially wrong. I rewrote it based on your comment – Michael Mrozek Aug 10 '10 at 20:34
Something I found out recently: you can redirect input to loops (for, while, etc.). See faqs.org/docs/abs/HTML/redircb.html. – Lucas Jones Aug 11 '10 at 10:41
Conventionally you put the redirection on the end. Whilst the pipeline metaphor looks better with <input foo | bar | baz >output, it doesn't work if you try mixing in some shell looping primitives like while or for in the middle. So I gave up and just put it at the end as per convention. – jmtd May 10 '11 at 13:07
@jmtd Well, putting it on the end eliminates "This is particularly useful for grep, as it allows you to place the expression at the end of the line, so you can quickly modify a grep command it by hitting Up, without needing to scroll left to get past the filename" – Michael Mrozek May 10 '11 at 13:42

You can use CDPATH to set up the directory equivalent of PATH; if you try to cd foo and there is no foo in the current directory, the shell will check each of the directories in CDPATH looking for foo in them, and switch to the first one it finds:

export CDPATH="/usr"
cd bin # switches to 'bin' if there is one in the current directory, or /usr/bin otherwise
This might cause issues. See softpanorama.org/Scripting/Shellorama/cdpath.shtml "If $CDPATH is set, the cd built-in will not implicitly append the current directory to it. This means that cd will fail if no valid directory name can be constructed from any of the entries in $CDPATH, even if a directory with the same name as the name given as an argument to cd exists in the current directory." I have been bitten by this, some Makefile's stopped working. Appending . explicitly might help though, but there are some issues with that as well. – ustun Aug 19 '10 at 9:22
vi `which scriptname`

For when you don't know where something lives, and you don't care either.

I don't mean to keep plugging ZSH features, but I keep thinking of them as other people answer :). In ZSH you can do =foo to invoke which automatically, so vi =scriptname – Michael Mrozek Aug 10 '10 at 19:58
If you are having trouble looking up the backtick character you can also use $(scriptname) – Patrick Oct 16 '10 at 8:20

The ampersand. It puts your command in the background, so you can continue typing.

$> sudo updatedb &

Working along, and after a while you see:

[1] 17403

And your process is done! Great for things where you don't need to wait for them to terminate.

And if your app is GUI, you probably don't want it to keep in jobs. Append &! to background the job and disown it from the shell! – progo Mar 15 '11 at 11:01
@progo: That doesn't work for me in bash. – Nathan Osman May 6 '11 at 2:07
@George. It seems that you're right. I did learn that zsh supported it, and later I heard that bash also supported it. Oh my :( – progo May 6 '11 at 4:28
@progo: It turns out that prepending the command with nohup accomplishes this. – Nathan Osman May 6 '11 at 6:37

Tab completion. How bad would it suck if you had to type out all the characters of every path?

There's suicide linux. If you incorrectly type the command - it does rm -fr /. So yeah, Tab completion is pretty vital... – Eimantas Aug 21 '10 at 4:58
Not as bad as you might think (but still bad), you just sprinkle wildcards everywhere: ls /usr/lib/game-d*/rott* – jmtd May 10 '11 at 13:08
@Eimantas Isn't rm -rf / disabled in most Linux systems? – Bernhard Heijstek Jul 9 '11 at 7:02
@phycker - I mentioned Suicide Linux, not "all". – Eimantas Jul 10 '11 at 14:25

Umount last mounted device:

mount /media/whatever

!mo expands to the last command that started with mo (at least in bash). Sometimes one does mv in the middle, so u!m won't work as often.

Use Ctrl+Shift+6 (Ctrl+^) to expand the command without running it as a safety precaution – ColinM Mar 2 '12 at 21:48

I have this in my .bashrc

#shortcut for CTRL+C and CTRL+V
alias c-c='xclip -sel clip'
alias c-v='xclip -o -sel clip'


function find-all() {
    python -c "import re
import sys
for i in re.findall('$1', sys.stdin.read()):
    if type(i) == type(''):
        print i
        print i[0]"

And when I have html source code in clipboard and want to find all links I use

c-v | find-all 'href="([^"]*)"' | c-c

And I have all urls in clipboard

I also have this function

function lsq(){
    ls -lh $@ | tr -s ' ' | cut -d' ' -f5,8

which display size (human readable) and filename.

alias temp='cat /proc/acpi/thermal_zone/THRM/temperature'

this alias is for show temerature

function separate() {
    python -c "import sys,re; print '$1'.join(re.split('\s*', sys.stdin.read().strip()))";

with this function I can calculate product or sum of arguments.

alias sum='separate + | bc'
alias product='separate * | bc'

function split-join() {
    python -c "import sys,re; print '$2'.join(re.split('$1', sys.stdin.read().strip()))";

This is usefull function which split standard input separated by regex and then join the result.

function factorial() {
    seq -s* $1 | bc

factorial function

function wiki() { dig +short txt $1.wp.dg.cx; }

This function display wiki text over DNS

I also have three color funcions

function blue() {
    echo -e "\x1b[34m\x1b[1m"$@"\x1b[0m";

function green() {
    echo -e "\x1b[32m\x1b[1m"$@"\x1b[0m";

function red() {
    echo -e "\x1b[31m\x1b[1m"$@"\x1b[0m";


function md5check() {
    test `md5sum $2 | cut -d' ' -f1` = "$1" && green [OK] || red [FAIL]

This function validate file md5 hash.

this will show error message for a given code

function strerror() { python -c "import os; print os.strerror($1)"; }

You can print all messages with

alias all-errors='for i in `seq 131`; do echo -n "$i: "; strerror $i; done'

Another useful ZSH trick:

Treat the output of a command as a file:

emacs =(hg cat -r 100 somefile)

This opens an old version of a Mercurial-tracked file in emacs for syntax-highlighted viewing. Without that, I would have to mess around with hg revert, hg archive, or explicitly send hg cat output to a temporary file.

Of course, this works with any program that opens files, and any program that prints to standard output.

You can do this in bash with the <() – ScaryAardvark Aug 11 '10 at 9:45

A ZSH-specific feature is suffix aliases, set by giving alias the -s flag:

alias -s ext=program

If a given extension has a suffix alias, you can execute a file with that extention directly, and ZSH will launch the given program and pass the filename as an argument. So if the above alias is in effect, these lines are equivalent:

program /path/to/foo.ext
This is one thing I really missed about Windows... until I realized that "program" was always emacs, so I stopped using shell to open files and just used C-x C-f (duh). – harpo Feb 16 '11 at 4:11

One of my all-time favorite ZSH features is named directories. You can export a variable with a given name, with a value that points to a certain path:

export foo=/usr/bin

Now you can use ~foo in a command to refer to /usr/bin:

cd ~foo
cat ~foo/filename
if your prompt displays the current working directory, the names of the variables will also be used there as far as I remember. – Andre Holzner Jun 18 '11 at 16:34

See this question.

When you run ps ax | grep string:

[steve@sage-arch ~]$ ps ax | grep 'openbox'
 3363 ?        Ss     0:00 /usr/bin/openbox
 3382 ?        Ss     0:00 /usr/bin/ssh-agent -- /usr/bin/openbox-session
 3386 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3388 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3389 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3390 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 5100 pts/0    S+     0:00 grep openbox

the last line containing grep is somethings a bit anoying

You can rid yourself of this by running ps ax | grep '[s]tring':

[steve@sage-arch ~]$ ps ax | grep '[o]penbox'
 3363 ?        Ss     0:00 /usr/bin/openbox
 3382 ?        Ss     0:00 /usr/bin/ssh-agent -- /usr/bin/openbox-session
 3386 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3388 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3389 ?        S      0:00 /bin/sh /usr/bin/openbox-session
 3390 ?        S      0:00 /bin/sh /usr/bin/openbox-session

update: or just run pgrep string

yeah, very useful. You should quote openbox though ('[o]penbox'). The brackets will work as kind of a glob, so if there is openbox in your directory (say you're in /usr/bin) bash will just use openbox, which will prevent the grep trick. – Rich Homolka Oct 21 '10 at 19:58
  • The do-nothing command : as in

    while :; do :; done
  • Brace expansion in combination with for loops:

    for c in {1..3}; do :; done
  • ! operator and short circuiting operators || and &&

    [ -d /tmp/dir ] || mkdir /tmp/dir
    if ! ping; then :; fi
  • using sub shells instead of pop/push (comes in handy in scripts)

    ~$ ( cd /tmp; echo $PWD )
  • the kind-of what-is command type

    ~$ type type
    type is a shell builtin
    ~$ type ls
    ls is aliased to `ls --color=auto'
    ~$ f(){ :; }
    ~$ type f
    f is a function
    f () 
  • also very nice: here-strings

    ~$ cat <<<"here $PWD"
    here /home/yourname
  • and my favorite: redirection on a list of commands

    { w; ps; ls /tmp; } 2>/dev/null |less

I love chucking as much stuff as I can into my PS1. Some useful things to remember:

\e[s and \e[u save and unsave the cursor position respectively. I use this to create an 'info-bar' at the top of the screen, a couple of lines long, which can fit more stuff. Example:

PS1='\[\e[s\e[7m\e[1;1H\]\w\n\t        \j / \! / \#\[\e[u\e[0m\e[33;1m\][\u@\h \[\e[34m\]\W]\[\e[0m\]\$ '

Combine with alias clear='echo -e "\e[2J\n"'. Try it out!

Also, the PROMPT_COMMAND variable defines a command to execute before the PS1 every time.

Another one is the bg command. If you forget to put & at the end of a command, just press ^Z and type bg, and it runs in the background.

thanks for the bg, when I have a program running in the background and accidentally press fg I don't know how to push it back :D – phunehehe Aug 11 '10 at 7:15
I like a clean PS1 so I put most of the stuff I want into my screen bottom line... – Josh Dec 14 '10 at 16:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.