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. See the help center for guidance on writing a good question.

Read more about locked posts here.

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
  • 3
    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
  • 1
    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
  • 1
    @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
  • 1
    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
  • 1
    To run previous commands looked up by a string, I usually just press Ctrl-R. Multiple Ctrl-R will dig deeper into the history. This way, I see the found command immediately, and can discard it and look further. Ctrl-G escapes from this mode. The only inconvenience is that Ctrl-R is for bash; in Emacs, to browse through the history of input commands and values (for M-x or other read values) one uses Meta-R instead (Meta-R is also used in eshell in Emacs). So I often mess them up. – imz -- Ivan Zakharyaschev Mar 16 '11 at 1:45

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.

  • 11
    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
  • 4
    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
  • 2
    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.

   Oct   Dec   Hex   Char                        Oct   Dec   Hex   Char
   000   0     00    NUL '\0' (null character)   100   64    40    @
   001   1     01    SOH (start of heading)      101   65    41    A
   002   2     02    STX (start of text)         102   66    42    B
   003   3     03    ETX (end of text)           103   67    43    C
   004   4     04    EOT (end of transmission)   104   68    44    D
   005   5     05    ENQ (enquiry)               105   69    45    E
   006   6     06    ACK (acknowledge)           106   70    46    F
   007   7     07    BEL '\a' (bell)             107   71    47    G
   010   8     08    BS  '\b' (backspace)        110   72    48    H
   011   9     09    HT  '\t' (horizontal tab)   111   73    49    I
   012   10    0A    LF  '\n' (new line)         112   74    4A    J
   013   11    0B    VT  '\v' (vertical tab)     113   75    4B    K
   014   12    0C    FF  '\f' (form feed)        114   76    4C    L
   015   13    0D    CR  '\r' (carriage ret)     115   77    4D    M
   016   14    0E    SO  (shift out)             116   78    4E    N
   017   15    0F    SI  (shift in)              117   79    4F    O
   020   16    10    DLE (data link escape)      120   80    50    P
   021   17    11    DC1 (device control 1)      121   81    51    Q
   022   18    12    DC2 (device control 2)      122   82    52    R
   023   19    13    DC3 (device control 3)      123   83    53    S
   024   20    14    DC4 (device control 4)      124   84    54    T
   025   21    15    NAK (negative ack.)         125   85    55    U
   026   22    16    SYN (synchronous idle)      126   86    56    V
   027   23    17    ETB (end of trans. blk)     127   87    57    W
   030   24    18    CAN (cancel)                130   88    58    X
   031   25    19    EM  (end of medium)         131   89    59    Y
   032   26    1A    SUB (substitute)            132   90    5A    Z
   033   27    1B    ESC (escape)                133   91    5B    [
   034   28    1C    FS  (file separator)        134   92    5C    \  '\\'
   035   29    1D    GS  (group separator)       135   93    5D    ]
   036   30    1E    RS  (record separator)      136   94    5E    ^
   037   31    1F    US  (unit separator)        137   95    5F    _
   040   32    20    SPACE                       140   96    60    `
   041   33    21    !                           141   97    61    a
   042   34    22    "                           142   98    62    b
   043   35    23    #                           143   99    63    c
   044   36    24    $                           144   100   64    d
   045   37    25    %                           145   101   65    e
   046   38    26    &                           146   102   66    f
   047   39    27    '                           147   103   67    g
   050   40    28    (                           150   104   68    h
   051   41    29    )                           151   105   69    i
   052   42    2A    *                           152   106   6A    j
   053   43    2B    +                           153   107   6B    k
   054   44    2C    ,                           154   108   6C    l
   055   45    2D    -                           155   109   6D    m

   056   46    2E    .                           156   110   6E    n
   057   47    2F    /                           157   111   6F    o
   060   48    30    0                           160   112   70    p
   061   49    31    1                           161   113   71    q
   062   50    32    2                           162   114   72    r
   063   51    33    3                           163   115   73    s
   064   52    34    4                           164   116   74    t
   065   53    35    5                           165   117   75    u
   066   54    36    6                           166   118   76    v
   067   55    37    7                           167   119   77    w
   070   56    38    8                           170   120   78    x
   071   57    39    9                           171   121   79    y
   072   58    3A    :                           172   122   7A    z
   073   59    3B    ;                           173   123   7B    {
   074   60    3C    <                           174   124   7C    |
   075   61    3D    =                           175   125   7D    }
   076   62    3E    >                           176   126   7E    ~
   077   63    3F    ?                           177   127   7F    DEL

Have a look at this website commandlinefu.com.

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

  • 2
    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 !!

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
  • 5
    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!

  • 8
    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)
  • 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) ))
  • 3
    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"
  • 5
    +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
  • 4
    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
  • 2
    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
  • 2
    Yes! alias u=pushd; alias o=popd – cannedprimates Aug 15 '10 at 9:57
  • 2
    .. 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
  • 2
    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". – unperson325680 Mar 15 '11 at 11:00
  • 1
    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 ;-) – Robert Swisher Aug 24 '10 at 22:19
  • 1
    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
  • 2
    s/fast/sloppy/ – Josh Dec 14 '10 at 16:00
  • 1
    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
  • 2
    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'
  • 3
    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
  • 3
    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.

  • 8
    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.

  • 11
    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! – unperson325680 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 :( – unperson325680 May 6 '11 at 4:28
  • 1
    @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?

  • 5
    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.

  • 5
    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.