Difference between revisions of "Bash"

From ArchWiki
Jump to: navigation, search
(Invocation: New section:Trying to make sense of Bash invocation. Correction/help welcome. Add resources link.)
m (Improved note to the extract function.)
Line 175: Line 175:
  
 
         command $c "$i"
 
         command $c "$i"
         e=$?
+
         e=$?З
 
     done
 
     done
  
Line 182: Line 182:
 
</nowiki>}}
 
</nowiki>}}
  
{{note|[[Bash]] users should make sure extglob is enabled: {{codeline|shopt -s extglob}}. It is enabled by default if using [[Bash#Advanced completion|Bash completion]]. [[Zsh]] users should do: {{codeline|setopt kshglob}} instead.}}
+
{{note|[[Bash]] users should make sure extglob is enabled: {{codeline|shopt -s extglob}}, for example by adding it to the {{Filename|.bashrc}}. It is enabled by default if using [[Bash#Advanced completion|Bash completion]]. [[Zsh]] users should do: {{codeline|setopt kshglob}} instead.}}
  
 
Another way to do this is to install ''unp'' package.
 
Another way to do this is to install ''unp'' package.

Revision as of 23:26, 16 October 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 – فارسی

Summary help replacing me
Discussing and improving Bash's capabilities.
Related
Readline
Environment Variables
Color Bash Prompt

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.

Invocation

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

Login shell

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

Interactive shell

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

POSIX compliance

Bash can be run with enhanced POSIX compliance by starting Bash with the Template:Codeline command-line option or executing ‘Template:Codeline’ while Bash is running.

Legacy mode

In Arch Template:Filename (which used to be the Bourne shell executable) is symlinked to Template:Filename.

If Bash is invoked with the name Template:Codeline, it tries to mimic the startup behavior of historical versions of Template:Codeline as closely as possible, while conforming to the posix standard as well.

In this mode, bash sources the startup files and then enters POSIX compliance.

Configuration

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: please use the first argument of the template to provide a brief explanation. (Discuss in Talk:Bash#)

Configuration file overview

An overview of the commonly used configuration files:

/etc/profile

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

.profile

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

.bashrc

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.

Configuration file sourcing order

These files are sourced by bash in different circumstances.

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.

Examples of the user dotfiles can be found in Template:Filename.

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

Shell and environment variables

The behavior of bash and programs run by it can be influenced by a number of environment variable. 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[1].

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 Template:Filename or Template:Filename 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.

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 Template:Filename, and system-wide aliases (which affect all users) belong in Template:Filename.

An example excerpt from Template:Filename covering several time-saving aliases: Template:File

Functions

Bash also support functions. The following function will extract a wide range of compressed file types. Add the function to Template:Filename and use it with the syntax Template:Codeline

Template:File

Note: Bash users should make sure extglob is enabled: Template:Codeline, for example by adding it to the Template:Filename. It is enabled by default if using Bash completion. Zsh users should do: Template:Codeline instead.

Another way to do this is to install unp package.

Tips and tricks

Prompt customization

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

#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 Template:Codeline 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.


Auto-completion

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

To do this add a 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

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

The Template:Package Official package extends functionality by adding auto-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 the readline initialization file (Template:Filename or Template:Filename by default):

set show-all-if-ambiguous on

it is no longer necessary to hit Template:Keypress (default binding) twice to produce a list of all possible completions (both when a partial completion is possible and when no completion is possible), as a single key-press will suffice. Alternatively, to produce such a list only when no completion is possible (i.e., not when a partial completion is possible), append the following command in lieu of the previous one:

set show-all-if-unmodified on

Disable Ctrl-Z in terminal

You can disable Template:Keypress+Template:Keypress (pauses/closes your CLI application) feature for you CLI by wrapping your command in this script

#!/bin/bash
trap "" 20
/path_to_your_application/

example:

#!/bin/bash
trap "" 20
/usr/bin/adom

With this example script, when you accidentally press Template:Keypress+Template:Keypress instead of Template:Keypress+Template:Keypress or some other key combo while playing Adom(game) your game will not end. Nothing will happen because Template:Keypress+Template:Keypress will be ignored.

Clear the screen after logging out

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

clear
reset

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 Template:Package Official package from the Template:Codeline repository.

Template:Cli

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, Template:Codeline 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 Template:Package Official. 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 Template:Codeline 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?         )
---------------------------------------- 
       o
         o
           o  
              ,'``.._   ,'``.
             :,--._:)\,:,._,.:
             :`--,@@@:`...';\        
              `,'@@@@@@@`---'@@`.     
              /@@@@@@@@@@@@@@@@@:
             /@@@@@@@@@@@@@@@@@@@\
           ,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.
          `...,---'``````-..._@@@@|:@@@@@@@\
            (                 )@@@;:@@@@)@@@\  _,-.
             `.              (@@@//@@@@@@@@@@`'@@@@\
              :               `.//@@)@@@@@@)@@@@@,@;
              |`.            _,'/@@@@@@@)@@@@)@,'@,'
              :`.`-..____..=:.-':@@@@@.@@@@@_,@@,'
             ,'\ ``--....-)='    `._,@@\    )@@@'``._
            /@_@`.       (@)      /@@@@@)  ; / \ \`-.'
           (@@@`-:`.     `' ___..'@@_,-'   |/   `.)
            `-. `.`.``-----``--,@@.'
              |/`.\`'        ,',');
                  `         (/  (/
(user@host)-(10:10 AM Wed Dec 22)--(~))--->

ASCII Historical Calendar

To install calendar files in your Template:Filename 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);

Resources