---
title: bash Tips & Tricks
layout: default
created: 2008-08-01 22:41:34 +0200
updated: 2009-02-08 14:32:54 +0100
toc: false
tags:
  - know-how
  - software
  - linux
  - software
  - bash
---
Bourne Again Shell.


bash magic
==========

Some handy `bash` magic.


sudo last command
-----------------

    sudo !!

If you forgot `sudo` after executing your 3-lines-command, sudo *bang! bang!* will repeat the last entered command with `sudo` prefixed.


More parameter magic
--------------------

| *bang*     | Expands to |
|:----------:|:-----------|
|  `!$`      | last argument of previous command      |
|  `!$:p`    | just show last argument of previous command, don't add to commandline |
|  `!*`      | **all** arguments of previous command  |
|  `!!:1`    | first argument of previous command     |
|  `!vi`     | last command that started with "*vi*"  |
|  `!vi:p`   | just show last "*vi*"-call, don't run it again  |
|  `^err^corr`  | replace all occurrences of `err` by `corr` in the last command  |


Shortcuts
---------

| *keypress*   | Description    |
|:------------:|:---------------|
|  <kbd>Ctrl</kbd>+<kbd>w</kbd>  | Erase word                              |
|  <kbd>Ctrl</kbd>+<kbd>u</kbd>  | Erase from cursor to beginning of line  |
|  <kbd>Ctrl</kbd>+<kbd>a</kbd>  | Move cursor to beginning of line        |
|  <kbd>Ctrl</kbd>+<kbd>e</kbd>  | Move cursor to end of line              |
|  <kbd>Ctrl</kbd>+<kbd>r</kbd>  | Search command history (type letters after this)  |


chdir to last one
-----------------

    cd -

Changes to previous directory.


Use output of previous command
------------------------------

Sometimes it's handy to use the output of a previous command, e.g. a `which`. To do that, simply use the *bang-bang* with the backtick operator:

    $ which php
    /usr/bin/php
    $ ls -l `!!`
    ls -l `which php`
    lrwxrwxrwx 1 root root 21 2008-06-12 02:47 /usr/bin/php -> /etc/alternatives/php
    $ _
