Bash - ArchWiki

# Bash

Related articles

- Bash/Functions
- Environment variables
- Readline
- Color Bash Prompt
- Fortune
- Pkgfile

Bash (Bourne-again Shell) is a command-line 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.

## Invocation

This article or section needs language, wiki syntax or style improvements.

Reason: Some duplication left, cryptic explanations (Discuss)

This article or section needs expansion.

Reason: Expand on non-interactive shells, see Talk:Bash#Return in non interactive mode (Discuss)

Bash behaviour can be altered depending on how it is invoked. Some descriptions of different modes follow.

If Bash is spawned by `login` in a tty, by an SSH daemon, or similar means, it is considered a login shell. This mode can also be engaged using the `-l` or `--login` command line options.

Bash is considered an interactive shell if it is started neither with the `-c` option nor any non-option arguments, and whose standard input and error are connected to terminals.

### Legacy mode

In Arch `/bin/sh` (which used to be the Bourne shell executable) is symlinked to `/bin/bash`. If Bash is invoked with the name `sh`, it tries to mimic the startup behavior of historical versions of `sh`, including POSIX compability.

A login shell run in legacy mode sources `/etc/profile`, then `~/.profile`.

### Configuration files

File | When file commands are read and executed (sourced)
--- | ---
`/etc/profile` | An interactive shell that is also a login shell (for example, from `/usr/bin/login`). Sources application settings in `/etc/profile.d/*.sh`, and `/etc/bash.bashrc`.
`/etc/bash.bashrc` | An interactive shell (for example, a terminal emulator). Depends on the `-DSYS_BASHRC="/etc/bash.bashrc"` compilation flag. Sources `/usr/share/bash-completion/bash_completion`.
`~/.bash_profile` | An interactive shell that is also a login shell. Per-user, after `/etc/profile`. If this file does not exist, `~/.bash_login` and `~/.profile` are checked in that order. The skeleton file `/etc/skel/.bash_profile` also sources `~/.bashrc`.
`~/.bashrc` | An interactive shell. Per-user, after `/etc/bash.bashrc`.
`~/.bash_logout` | After exit of a login shell.

In short, all interactive shells source `/etc/bash.bashrc` and `~/.bashrc`, while interactive login shells also source `/etc/profile` and `~/.bash_profile`.

Note: While interactive, non-login shells do not source `~/.bash_profile`, they still inherit the environment from their parent process (which may be a login shell). See [1] for details.

See the INVOCATION section of `man 1 bash` or [2] for the complete sequence.

### Shell and environment variables

This article or section is a candidate for merging with #Configuration files.

Notes: Duplication (Discuss)

The behavior of Bash and programs run by it can be influenced by a number of environment variables. Environment variables are used to store useful values such as command search directories, or which browser to use. When a new shell or script is launched it inherits its parent's variables, thus starting with an internal set of shell variables[3].

These shell variables in Bash can be exported in order to become environment variables:

    VARIABLE=content
    export VARIABLE

or with a shortcut

    export VARIABLE=content

Environment variables are conventionally placed in `~/.profile` or `/etc/profile` so that all bourne-compatible shells can use them.

See Environment variables for more general information.

## Command line

Bash command line is managed by the separate library called Readline. Readline provides a lot of shortcuts for interacting with the command line i.e. moving back and forth on the word basis, deleting words etc. It is also Readline's responsibility to manage history of input commands. Last, but not least, it allows you to create macros.

### Tab completion

Tab completion is the option to auto-complete partial typed commands by pressing `Tab` twice (enabled by default).

#### Single-tab ability

For single press `Tab` results for when a partial or no completion is possible:

    ~/.inputrc

    set show-all-if-ambiguous on

Alternatively, for results when no completion is possible:

    ~/.inputrc

    set show-all-if-unmodified on

#### Additional programs and options

Bash has native support for for tab completion of: commands, filenames, and variables. This functionality can be extended with the package bash-completion; it extends its functionality by adding a subset of tab completions to popular commands and their options. With bash-completion know that normal completions (such as `$ ls file.*<tab><tab>`) will behave different; however, they can be re-enabled with `$ compopt -o bashdefault <prog>` (see [4] and [5] for more detail). Also for older systems bash-completion may not be resourcefully convenient.

#### Additional programs and options manually

For basic completion use lines in the form of `complete -cf your_command` (these will conflict with the bash-completion settings):

    ~/.bashrc

    complete -cf sudo
    complete -cf man

### History completion

History completion bound to arrow keys (down, up) (see: Readline#History and Readline Init File Syntax):

    ~/.bashrc

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

or:

    ~/.inputrc

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

### Fast word movement with Ctrl

Bash allows to quickly move between words with `Ctrl+Left` and `Ctrl+Right`.

    ~/.inputrc

    "\e[1;5C": forward-word
    "\e[1;5D": backward-word
    "\e[5C": forward-word
    "\e[5D": backward-word
    "\e\e[C": forward-word
    "\e\e[D": backward-word

### Mimic Zsh run-help ability

Zsh can invoke the manual for the written command pushing `Alt+h`. A similar behaviour is obtained in Bash by appending this line in your `inputrc` file:

    /etc/inputrc

    "\eh": "\C-a\eb\ed\C-y\e#man \C-y\C-m\C-p\C-p\C-a\C-d\C-e"

## Aliases

alias is a command, which enables a replacement of a word with another string. It is often used for abbreviating a system command, or for adding default arguments to a regularly used command.

Personal aliases are preferably stored in `~/.bashrc`, and system-wide aliases (which affect all users) belong in `/etc/bash.bashrc`. See [6] and Pacman tips#Shortcuts for example aliases.

For functions, see Bash/Functions.

## Tips and tricks

### Prompt customization

This article or section needs expansion.

Reason: Mention `PS2` to `PS4`[7] (Discuss)

This article or section is a candidate for merging with Color Bash Prompt.

Notes: please use the second argument of the template to provide more detailed indications. (Discuss)

The Bash prompt is governed by the variable `$PS1`. To colorize the Bash prompt, use:

    ~/.bashrc

    #PS1='[\u@\h \W]\$ '  # To leave the default one
    #DO NOT USE RAW ESCAPES, USE TPUT
    reset=$(tput sgr0)
    red=$(tput setaf 1)
    blue=$(tput setaf 4)
    green=$(tput setaf 2)

    PS1='\[$red\]\u\[$reset\] \[$blue\]\w\[$reset\] \[$red\]\$ \[$reset\]\[$green\] '

This `$PS1` is useful for a root Bash prompt, with red designation and green console text. For more info, see: Color Bash Prompt.

#### Customize title

The `$PROMPT_COMMAND` variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:

    ~/.bashrc

    export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'

This will change your title to the last command run, and make sure your history file is always up-to-date:

    ~/.bashrc

    export HISTCONTROL=ignoreboth
    export HISTIGNORE='history*'
    export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\}  //g";echo -en "\e\\";'

### Command-not-found (AUR)

pkgfile includes a "command not found" hook that will automatically search the official repositories, when entering an unrecognized command. An alternative "command not found" hook is provided by the AUR package command-not-found. Usage example:

    $ abiword

    The command 'abiword' is been provided by the following packages:
    abiword (2.8.6-7) from extra
    	[ abiword ]
    abiword (2.8.6-7) from staging
    	[ abiword ]
    abiword (2.8.6-7) from testing
    	[ abiword ]

To load it automatically:

    ~/.bashrc or ~/.zshrc

    [ -r /etc/profile.d/cnf.sh ] && . /etc/profile.d/cnf.sh

### Disable Ctrl+z in terminal

You can disable the `Ctrl+z` feature (pauses/closes your application) by wrapping your command like this:

    #!/bin/bash
    trap "" 20
    adom

Now when you accidentally press `Ctrl+z` in adom instead of `Shift+z` nothing will happen because `Ctrl+z` will be ignored.

### Clear the screen after logging out

To clear the screen after logging out on a virtual terminal:

    ~/.bash_logout

    clear
    reset

### ASCII historical calendar

To install calendar files in your `~/.calendar` directory you will need the rpmextract package installed. Then from your home directory, run the following:

    $ mkdir -p ~/.calendar
    $ curl -o calendar.rpm ftp://ftp.univie.ac.at/systems/linux/fedora/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);

### Auto "cd" when entering just a path

Bash can automatically prepend `cd` when entering just a path in the shell. For example:

    $ /etc

    bash: /etc: Is a directory

But after:

    ~/.bashrc

    shopt -s autocd

You get:

    [user@host ~] $ /etc
    cd /etc
    [user@host etc]

## Troubleshooting

### Line wrap on window resize

When resizing a terminal emulator, Bash may not receive the resize signal. This will cause typed text to not wrap correctly and overlap the prompt. The `checkwinsize` shell option checks the window size after each command and, if necessary, updates the values of `LINES` and `COLUMNS`.

    ~/.bashrc

    shopt -s checkwinsize

## See also

- Bash Reference
- Bash manual page
- Readline Init File Syntax
- The Bourne-Again Shell - The third chapter of The Architecture of Open Source Applications
- Shellcheck - Check bash scripts for common errors

### Tutorials

- BashGuide on Greg's Wiki
- BashFAQ on Greg's Wiki
- Bash Hackers Wiki
- Advanced Bash Scripting Guide
- Bash Scripting by Example
- Quote Tutorial
- Introduction to Bash

### Community

- An active and friendly IRC channel for Bash
- Bashscripts.org

### Examples

- How to change the title of an xterm

Category:

- Command shells