Difference between revisions of "Bash"

From ArchWiki
Jump to: navigation, search
(Tips and tricks: moved from Startup files, which is being merged into Autostarting)
(#bash freenode)
Line 299: Line 299:
* [http://tiswww.case.edu/php/chet/readline/rluserman.html Readline Guide]
* [http://tiswww.case.edu/php/chet/readline/rluserman.html Readline Guide]
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]
IRC #bash channel is a very good place to ask question about bash with a quite good activity all the time and skilled & nice people. --[[User:Sputnick|Sputnick]] 14:09, 27 July 2011 (EDT)

Revision as of 18:09, 27 July 2011

This template has only maintenance purposes. For linking to local translations please use interlanguage links, see Help:i18n#Interlanguage links.

Local languages: Català – Dansk – English – Español – Esperanto – Hrvatski – Indonesia – Italiano – Lietuviškai – Magyar – Nederlands – Norsk Bokmål – Polski – Português – Slovenský – Česky – Ελληνικά – Български – Русский – Српски – Українська – עברית – العربية – ไทย – 日本語 – 正體中文 – 简体中文 – 한국어

External languages (all articles in these languages should be moved to the external wiki): Deutsch – Français – Română – Suomi – Svenska – Tiếng Việt – Türkçe – فارسی

Template:Article summary start Template:Article summary text Template:Article summary heading Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary end Bash (Bourne-again Shell) is a shell/programming language by the GNU Project. Its name is a homaging reference to its predecessor: the long-deprecated Bourne shell. Bash can be run on most UNIX-like operating systems, including GNU/Linux. Arch copiously uses Bash throughout its init-scripts.


These files are sourced by bash in different circumstances. When an interactive and login shell is started, it will source Template:Filename, and the first of Template:Filename, Template:Filename and Template:Filename that exists and is readable. Bash will source Template:Filename upon exit. However, when a non-login interactive shell is started, it will only source Template:Filename and Template:Filename. Examples of the user dotfiles can be found in Template:Filename.

An overview of the commonly used configuration files:


Template:Filename is sourced by all Bourne-compatible shells upon login. It sets up a environment upon login and application-specific (Template:Filename) settings.


This file is read and sourced by bash when an interactive login shell is started.


The file Template:Filename is read and sourced by bash when a non-login interactive shell is started, for example, when you open a virtual console from the desktop environment. This file is useful for setting up a user-specific shell environment.

Environment variables

Template:Moveto All of these should be exported in order to become environment variables instead of shell variables:


Environment variables are conventionally placed in Template:Filename or Template:Filename so that all bourne-compatible shells can use them.


The web browser. Helpful to set in an interactive shell configuration file so that it may be dynamically altered depending on the availability of a graphic environment, such as X:

if [ -n "$DISPLAY" ]; then


Should point to a lightweight text editor, such as ed or ex. Convenient for editing SCM commit logs that don't require a whole lot of features from the application. ex has more features, but it will clear the whole screen, while ed does not.

FTP and HTTP proxy

FTP and HTTP proxy server, respectively:



The location of incoming email. The traditional setting is Template:Filename.


The pager called by man and other applications; for example, less, or more.


The PATH variable is a string delimited by colons (:) which specifies the directories to search for when users enter a command name without an explicit path preface. If the command is found in the directories specified in PATH, the program is executed.

Note: It's advised not to include the current working directory (.) into your PATH for security reasons, as it may trick the user to execute vicious commands.


Regards full-fledged editors that are used for more demanding tasks, such as editing mail; e.g., vi, vim, emacs, etc.

Tips and tricks

Prompt customization

The bash prompt is governed by the variable $PS1. To colorize the bash prompt, first comment out the default $PS1:

#PS1='[\u@\h \W]\$ '

Then add the following line:

PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '

This $PS1 is useful for a root bash prompt, with red designation and green console text. For details on customizing your bash prompt, see Color Bash Prompt.


An Alias substitutes a word with a user-defined string, this is useful for creating abbreviations of a command or adding default arguments to a command.

For example, to make rm prompt before every removal:

alias rm='rm -i'

or once before removing more than three files and when removing recursively

alias rm='rm -I'

To make cp and mv prompt for overwrite:

alias cp='cp -i'
alias mv='mv -i'

To use vi instead of nano (to force someone to learn vi):

alias nano='vi'


It is useful to have the auto-complete feature (pressing Tab key twice on the keyboard) after you type some command like sudo.

To do this add line in this format to your Template:Filename file:

complete -cf your_command

For example, to enable auto-complete after sudo and man:

complete -cf sudo
complete -cf man

Advanced completion

In spite of bash's native support for basic file name, command and variable auto-completion, there are ways of improving and extending its reach.

The bash-completion package extends functionality by adding completion to a wide range of commands and their options. Enabling advanced bash completion is quite simple, just install the following package:

# pacman -S bash-completion

Start a new shell and it will be automatically enabled thanks to Template:Filename.

Faster completion

By appending the following into Template:Filename or Template:Filename:

set show-all-if-ambiguous on

it is no longer necessary to hit Tab twice to produce a list of all possible completions, as a single key-press will suffice.

History search

Usually, pressing the up arrow key will cause the last command to be shown regardless of what has been typed so far. However, users may find it more practical to list only past commands that match the current input.

For example, if the user has typed the following commands:

In this situation, when typing Template:Codeline and pressing the up arrow key, current input will be replaced with Template:Codeline, the last performed command. Had history search been enabled, only past commands beginning with Template:Codeline (the current input) would've been shown, in this case Template:Codeline.

You can enable this mode by adding the lines below to Template:Filename or Template:Filename:


If you chose to add the aforementioned two lines to Template:Filename, it is recommended that you also add the following line at the beginning of this file to avoid strange things like this:

$include /etc/inputrc

Alternatively, one can use reverse-search-history (incremental search) by pressing Template:Keypress+Template:Keypress, which does not search based on previous input but instead jumps backwards in the history buffer as commands are typed in a search term. Pressing Template:Keypress+Template:Keypress again during this mode will display the previous line in the buffer that matches the current search term, while pressing Template:Keypress+Template:Keypress (abort) will cancel the search and restore the current input line. So in order to search through all previous Template:Codeline commands, press Template:Keypress+Template:Keypress, type 'mount' and keep pressing Template:Keypress+Template:Keypress until the desired line is found.

The forward equivalent to this mode is called forward-search-history and is bound to Template:Keypress+Template:Keypress by default. Beware that most terminals override Template:Keypress+Template:Keypress to suspend execution until Template:Keypress+Template:Keypress is entered. (This is called XON/XOFF flow control). For activating forward-search-history, either disable flow control by issuing:

$ stty -ixon

or use a different key in Template:Filename. For example to use Alt+S, which is not bound by default:


Avoid duplicates

If you repeat the same command several times, they will all be appended in your history. To prevent this, add to your Template:Filename:

export HISTCONTROL=ignoredups

Avoid whitespaces

To disable logging blank commands add this to your Template:Filename:

export HISTCONTROL=ignorespace

If your Template:Filename already contains

export HISTCONTROL=ignoredups

replace it with

export HISTCONTROL=ignoreboth

Disable control-z in terminal

You can disable ctrl-z(pauses/closes your CLI application) feature for you CLI by wrapping your command in this script

trap "" 20


trap "" 20

With example script when you accidentially press ctrl+z instead of shift+z or some other key combo while playing Adom(game) your game won't end. Nothing will happen because ctrl+z will be ignored.

Disabling control echo

Due to an update to Template:Package Official, the terminal now echoes Template:Codeline after Template:Keypress+Template:Keypress is pressed. For users who wish to disable this, simply add the following to Template:Filename:

set echo-control-characters off

Readline macros

Readline also supports binding keys to keyboard macros. For simple example, run this command in bash:

bind '"\ew":"\C-e # macro"'

or add the part within single quotes to inputrc:

"\ew":"\C-e # macro"

Now type a line and press Alt+W. Readline will act as though Ctrl+E (end-of-line) had been pressed, appended with 'Template:Codeline'.

Use any of the existing keybindings within a readline macro, which can be quite useful to automate frequently used idioms. For example, this one makes Ctrl+Alt+L append "| less" to the line and run it (Ctrl+M is equivalent to Enter:

"\e\C-l":"\C-e | less\C-m"

The next one prefixes the line with 'yes |' when pressing Ctrl+Alt+Y, confirming any yes/no question the command might ask:

"\e\C-y":"\C-ayes | \C-m"

This example wraps the line in su -c '' if Alt+S is pressed:

"\es":"\C-a su -c '\C-e'\C-m"

As a last example, quickly send a command in the background with Ctrl+Alt+B, discarding all its output:

"\e\C-b":"\C-e > /dev/null 2>&1 &\C-m"

Command-line editing

As stated above, bash is readline-powered. Therefore you may find the readline instructions in the GNU Bash manual or the shortcuts table at www.bigsmoke.us very useful.

If you are a vi or vim user, you may want to put the following line to your Template:Filename to enable vi-like keybindings:

set -o vi

Taken from www.catonmat.net

Startup files

There are different possibilities:

But, in Arch, by default:

which means that Template:Filename and Template:Filename will be executed for all interactive shells, whether they are login shells or not.

Note: legacy mode is when invoked with the name Template:Codeline

Clear the screen after logging out

To clear the screen after logging out on a virtual terminal, append the following lines to Template:Filename:


ASCII art, fortunes and cowsay

Along with a colors, system info and ASCII symbols, BASH can be made to display a piece of ASCII art on login. ASCII images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, place the string cat /path/to/text/file at the top of Template:Filename.

Random poignant, inspirational, silly or snide phrases can also be shown. To see an example, install the fortune-mod package from the extra repository.


To have a random phrase displayed when logging into a terminal, just set command fortune as the top line in Template:Filename.

Note: By default, fortune displays quotes and phrases that are rather inoccuous. However, the package does contain a set of comments some will find offensive, located in Template:Filename. See the man page for more info on these.

These two features can be combined, using the program cowsay. Modify the line at the top of Template:Filename to read command cowsay $(fortune)or command cowthink $(fortune).

The earth is like a tiny grain of sand, 
only much, much heavier.                
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||

The ASCII images are generated by Template:Filename text files located in Template:Filename, and all themes can be listed with the command cowsay -l These files can be edited to the user's liking; custom images can also be created from scratch or found on the net. The easiest way create a custom cow file from an image found online would be to open an existing Template:Filename file in a text editor, copy-and-paste the image from a browser and save the file as a different name. Test the custom file using

# cowsay -f Template:Filename $(fortune)

This can produce some nice eye candy, and the commands used can be more complex. For a specialized example, take a look here.

( Fry: I must be a robot. Why else would )
( human women refuse to date me?         )
              ,'``.._   ,'``.
            (                 )@@@;:@@@@)@@@\  _,-.
             `.              (@@@//@@@@@@@@@@`'@@@@\
              :               `.//@@)@@@@@@)@@@@@,@;
              |`.            _,'/@@@@@@@)@@@@)@,'@,'
             ,'\ ``--....-)='    `._,@@\    )@@@'``._
            /@_@`.       (@)      /@@@@@)  ; / \ \`-.'
           (@@@`-:`.     `' ___..'@@_,-'   |/   `.)
            `-. `.`.``-----``--,@@.'
              |/`.\`'        ,',');
                  `         (/  (/
(user@host)-(10:10 AM Wed Dec 22)--(~))--->

ASCII Historical Calendar

To install calendar files in your ~/.calendar directory:

$ mkdir -p ~/.calendar
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*

This will then print out the calendar items

$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);


IRC #bash channel is a very good place to ask question about bash with a quite good activity all the time and skilled & nice people. --Sputnick 14:09, 27 July 2011 (EDT)