next up previous contents
Next: Environment Variables Up: Terminal Setup Previous: Login Setup

The BASH SHELL

The bash shell, bash, is a Unix shell written as a replacement for sh. Bash is a command processor, typically run in a text window, allowing the user to type commands which cause actions. Bash can also read commands from a file, called a script. Like all Unix shells, it supports filename wildcarding, piping, command substitution, variables and control structures for condition-testing and iteration. The keywords, syntax and other basic features of the language were all copied from sh. Other features, e.g., history, were copied from csh.

Initialization and Termination

When started as an interactive login shell Bash reads and executes /etc/profile (if it exists). (Often this file calls /etc/bash.bashrc.) After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile in that order, and reads and executes the first one that exists and is readable. When started as an interactive shell (but not a login shell) bash reads and executes ~/.bashrc (if it exists). This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

Lexical Structure

The characters & | ; < >( ) # form separate words. These shell metacharacters can be made part of other words and have their special meaning suppressed by preceding them with a backslash (\). In addition a string enclosed in matched pairs of single quotes or double quotes forms a partial word; again meta characters in such a string have their meaning suppressed.
# introduces a comment in a shell file (if used as input instead of terminal)
  that continues till the end of the input line
| the standard output of the command preceding it is redirected to the
  standard input of the command that follows

For example:
% man tcsh lpr -Pelprt2

prints the man pages on tcsh.

A pipeline is a simple command or a sequence of simple commands separated by '|' character. Sequences of pipelines can be separated by (;), in which case they are executed sequentially. A command can be executed asynchronously or in the background by appending an & rather than waiting for the sequence to finish, eg.,
% man tcsh|lpr; source obj|append|print &

History Substitution

Each command input from the terminal is saved in the history list. The previous command is always saved, and the history shell environment variable can be set to a number to save that many commands.

You can use the up-arrow and down-arrow keys to scroll through the history list and you may edit any command line in that history list.

Jobs

The shell keeps a table of current jobs that can be printed by the jobs command. A job is associated with each pipeline.

1.
A job may be referred to as %number, where the number is the value of the jobid. For example fg %1 brings job 1 to the foreground. Jobs can also be referred to by the prefixes of the string typed in to start them, provided the prefixes are unambiguous, such as %ex would refer to the suspended ex job. %% or %+ refers to the current job while %- refers to the previous job.
2.
A job may be started asynchronously with a & prefix to the command pipeline

3.
A job may be temporarily suspended by the key ^Z (ctrl-Z) or by stop %jobid. The shell will inform you that the job has been stopped.

4.
A job may be resumed in the background by bg %jobid, once it has been suspended or by %jobid &. A background job is normally allowed to produce output but this may be inhibited by stty tostop, in which case it will stop when it tries to produce output. Refer to section on Terminal Setup.

5.
A job may be resumed from its suspended state by fg %jobid or simply by %jobid.

6.
A job may be terminated by kill %jobid.

When you try to leave the shell while jobs are stopped, you will be warned There are stopped jobs. You may use the jobs command to see what they are. If you immediately try to exit again, the shell will not warn you and the suspended jobs will be automatically terminated.

Alias Substitution

It is convenient to name the available commands on the system according to your own mnemonics - this can be done by the alias command. For example, alias dir='ls -la' would allow the user to use the command dir in place of the command ls -la for getting a listing of files in the user's directory. Unalias allows you to remove the alias while alias when typed alone gives you the entire list of aliases created.

Variable Substitution

Global variables or environment variables are available in all shells. The env or printenv commands can be used to display environment variables.

Any reference to a variable starts with a $ and is replaced the value of that variable. Unless enclosed in "s the results of variable substitution may be command and filename substituted.
% echo $varname

prints out the value of the variable varname.

Command and Filename Substitution

Command and filename substitutions are applied selectively to the arguments of builtin commands. Command substitution is indicated by enclosing a command in single back quotes (`). The output from such a command, performed by a subshell, is broken into separate words at each space, tab and newline.
For example,

% echo `ls`

will print out the result of the command ls which in this case means a directory listing.

If a word contains any of the characters * ? [ { or begins with ~, then the word is open to filename substitution. Basically the word is regarded as a pattern and is replaced with an alphabetically sorted list of file names which match the pattern.

The matching rules are fairly standard -

* matches zero or more characters
? matches any single character
[...] matches any single character in the enclosed list(s) or range(s)
  A list is a string of characters while a range is two characters
  separated by a minus (-) sign and includes all characters in between
  according to the ASCII collating sequence
~[user] your home directory, as indicated by the value of the
  variable home, or that of the user, as indicated by
  the password entry for user
{str,str,..} expand to each string in the comma separated list

The dot (.) character or the slash (/), when it is the first character in a filename or pathname component, must be matched explicitly.
For example, "a{b,c,d}e" expands to "abe ace ade".

Input/Output

The standard input/output may be redirected with the following syntax:

< name open file name as the standard input
  (but first name is command/variable/filename expanded)
<< word read the shell input up to a line which is identical to word
> name the file name is used as standard output.
  If it exists its previous contents are lost.
&> name Route diagnostic output as well as standard output to file.
>> name appends standard output to file name
&>> name appends standard output and diagnostic output to file

Environment

The environment is a list of name-value pairs that is passed to an executed program. On invocation the shell scans the environment and creates a parameter for each valid name found, giving it the corresponding value. Executed commands inherit the same environment. If the user modifies the values of these parameters or creates new ones, none of these affects the environment unless the export command is used to bind the shell's parameter to the environment. The environment for any single command may be augmented by prefixing it with one or more assignments to parameters, for eg.,
TERM=450 <cmd> args

Typing set with no arguments gives a list of all the shell parameters that are set along with their values.

Command Execution

If a command is a builtin, then the shell executes it directly. Otherwise the shell searches for a file by that name with execute access, in every directory listed in the path variable.

If the search is successful, and the file has execute permission but is not an executable binary to the system, then it is assumed to be a file containing shell commands and a new shell is spawned to read it. If the first characters of the file are #! then a C-shell is invoked. Otherwise the Bourne shell is used. If the file is an executable the shell forks a new process and passes it to the kernel which then begins to execute the process.

The which filename command will look through your path to locate a file and tell you which one would be executed had the name been given as a command. The file filename command file determines the file type.

Shell Scripts

A file containing shell commands may be executed by
% source file

This will execute the commands in the file in the context of the current shell. Normally these commands are not put in the history list (see below).
The special files .bash_login, .bashrc, .aliases, .profile and the like belong to this category.

Alternatively, a file containing shell script commands can be given execute access by chmod command and then executed by simply typing its name. The important difference is that this executes the commands in a subshell and all the bindings are lost after the file is executed. The results do not affect the current context.

For example, consider the following shell script:

#!/bin/bash
foo=1
echo "done"

If you source this shell script you will find that the shell variable foo is set, if you make it executable the value is set but only in the context of the executing process.


next up previous contents
Next: Environment Variables Up: Terminal Setup Previous: Login Setup
Paul A. Sihvonen-Binder
8/8/2014