Shell Configuration - Shells - Ubuntu 15.04 Server with systemd: Administration and Reference (2015)

Ubuntu 15.04 Server with systemd: Administration and Reference (2015)

Part V. Shells

Chapter 22. Shell Configuration

Four different major shells are commonly used on Linux systems: the Bourne Again shell (BASH), the AT&T Korn shell, the TCSH shell, and the Z shell. The BASH shell is an advanced version of the Bourne shell, which includes most of the advanced features developed for the Korn shell and the C shell. TCSH is an enhanced version of the C shell, originally developed for BSD versions of UNIX. The AT&T UNIX Korn shell is open source. The Z shell is an enhanced version of the Korn shell. Although their UNIX counterparts differ greatly, the Linux shells share many of the same features. In UNIX, the Bourne shell lacks many capabilities found in the other UNIX shells. In Linux, however, the BASH shell incorporates all the advanced features of the Korn shell and C shell, as well as the TCSH shell. All four shells are available for your use, though the BASH shell is the default.

Command

Description

bash

BASH shell, /bin/bash

bsh

BASH shell, /bin/bsh (link to /bin/bash)

sh

BASH shell, /bin/sh (link to /bin/bash)

tcsh

TCSH shell, /usr/tcsh

csh

TCSH shell , /bin/csh (link to /bin/tcsh)

ksh

Korn shell, /bin/ksh (also added link /usr/bin/ksh)

zsh

Z shell, /bin/zsh

Table 22-1: Shell Invocation Command Names

The BASH shell is the default shell for most Linux distributions. If you are logging in to a command line interface, you will be placed in the default shell automatically and given a shell prompt at which to enter your commands. The shell prompt for the BASH shell is a dollar sign ($). In the GUI interface, such as GNOME or KDE, you can open a terminal window that will display a command line interface with the prompt for the default shell (BASH). Though you log in to your default shell or display it automatically in a terminal window, you can change to another shell by entering its name. Entering tcsh invokes the TCSH shell, bash the BASH shell, ksh the Korn shell, and zsh the Z shell. You can leave a shell by pressing CTRL-D or using the exit command. You only need one type of shell to do your work. Table 22-1 shows the different commands you can use to invoke different shells. Some shells have added links you can use to invoke the same shell, like sh and bsh, which link to and invoke the bash command for the BASH shell.

This chapter describes common features of the BASH shell, such as aliases, as well as how to configure the shell to your own needs using shell variables and initialization files. The other shells share many of the same features and use similar variables and configuration files.

Though the basic shell features and configurations are shown here, you should consult the respective online manuals and FAQs for each shell for more detailed examples and explanations.

Shell Initialization and Configuration Files

Each type of shell has its own set of initialization and configuration files. The TCSH shell uses .login, .tcshrc, and .logout files in place of .profile, .bashrc, and .bash_logout. The Z shell has several initialization files: .zshenv, .zlogin, .zprofile, .zschrc, and .zlogout. See Table 22-2for a listing. Check the Man pages for each shell to see how they are usually configured. When you install a shell, default versions of these files are automatically placed in the users’ home directories. Except for the TCSH shell, all shells use much the same syntax for variable definitions and assigning values (TCSH uses a slightly different syntax, described in its Man pages).

Filename

Function

BASH Shell

.profile

Login initialization file

.bashrc

BASH shell configuration file

.bash_logout

Logout name

.bash_history

History file

/etc/profile

System login initialization file

/etc/bash.bashrc

System BASH shell configuration file

/etc/profile.d

Directory for specialized BASH shell configuration files

/etc/bash_completion

Completion options for applications

TCSH Shell

.login

Login initialization file

.tcshrc

TCSH shell configuration file

.logout

Logout file

Z Shell

.zshenv

Shell login file (first read)

.zprofile

Login initialization file

.zlogin

Shell login file

.zshrc

Z shell configuration file

.zlogout

Logout file

Korn Shell

.profile

Login initialization file

.kshrc

KORN shell configuration file

Table 22-2: Shell Configuration Files

Configuration Directories and Files

Applications often install configuration files in a user’s home directory that contain specific configuration information, which tailors the application to the needs of that particular user. This may take the form of a single configuration file that begins with a period, or a directory that contains several configuration files. The directory name will also begin with a period. For example, Mozilla installs a directory called .mozilla in the user’s home directory that contains configuration files. On the other hand, many mail applications uses a single file called .mailrc to hold alias and feature settings set up by the user, though others like Evolution also have their own, .evolution. Most single configuration files end in the letters rc. FTP uses a file called .netrc. Most newsreaders use a file called .newsrc. Entries in configuration files are usually set by the application, though you can usually make entries directly by editing the file. Applications have their own set of special variables to which you can define and assign values. You can list the configuration files in your home directory with the ls -a command.

Aliases

You can use the alias command to create another name for a command. The alias command operates like a macro that expands to the command it represents. The alias does not literally replace the name of the command; it simply gives another name to that command. An alias command begins with the keyword alias and the new name for the command, followed by an equal sign and the command the alias will reference.

Note: No spaces should be placed around the equal sign used in the alias command.

In the next example, list becomes another name for the ls command:

$ alias list=ls
$ ls
mydata today
$ list
mydata today
$

If you want an alias to be automatically defined, you have to enter the alias operation in a shell configuration file. On Ubuntu, aliases are defined in either the user's .bashrc file or in a .bash_aliases file. To use a .bash_aliases file, you have to first uncomment the commands in the .bashrc file that will read the .bash_aliases file. Just edit the .bashrc file and remove the preceding # so it appears like the following:

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

You can also place aliases in the .bashrc file directly. Some are already defined, though commented out. You can edit the .bashrc file and remove the # comment symbols from those lines to activate the aliases.

# some more ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'

Aliasing Commands and Options

You can also use an alias to substitute for a command and its option, but you need to enclose both the command and the option within single quotes. Any command you alias that contains spaces must be enclosed in single quotes as well. In the next example, the alias lss references the ls command with its -s option, and the alias lsa references the ls command with the -F option. The ls command with the -s option lists files and their sizes in blocks, and ls with the -F option places a slash after directory names. Notice how single quotes enclose the command and its option.

$ alias lss='ls -s'
$ lss
mydata 14 today 6 reports 1
$ alias lsa='ls -F'
$ lsa
mydata today reports/
$

Aliases are helpful for simplifying complex operations. In the next example, listlong becomes another name for the ls command with the -l option (the long format that lists all file information), as well as the -h option for using a human-readable format for file sizes. Be sure to encase the command and its arguments within single quotes so that they are taken as one argument and not parsed by the shell.

$ alias listlong='ls -lh'
$ listlong
-rw-r--r-- 1 root root 51K Sep 18 2008 mydata
-rw-r--r-- 1 root root 16K Sep 27 2008 today

Aliasing Commands and Arguments

You may often use an alias to include a command name with an argument. If you execute a command that has an argument with a complex combination of special characters on a regular basis, you may want to alias it. For example, suppose you often list just your source code and object code files—those files ending in either a .c or .o. You would need to use as an argument for ls a combination of special characters such as *.[co]. Instead, you can alias ls with the .[co] argument, giving it a simple name. In the next example, the user creates an alias called lsc for the command ls.[co]:

$ alias lsc='ls *.[co]'
$ lsc
main.c main.o lib.c lib.o

Aliasing Commands

You can also use the name of a command as an alias. This can be helpful in cases where you should use a command only with a specific option. In the case of the rm, cp, and mv commands, the -i option should always be used to ensure an existing file is not overwritten. Instead of always being careful to use the -i option each time you use one of these commands, you can alias the command name to include the option. In the next example, the rm, cp, and mv commands have been aliased to include the -i option:

$ alias rm='rm -i'
$ alias mv='mv -i'
$ alias cp='cp -i'

The alias command by itself provides a list of all aliases that have been defined, showing the commands they represent. You can remove an alias by using the unalias command. In the next example, the user lists the current aliases and then removes the lsa alias:

$ alias
lsa=ls -F
list=ls
rm=rm -i
$ unalias lsa

Controlling Shell Operations

The BASH shell has several features that enable you to control the way different shell operations work. For example, setting the noclobber feature prevents redirection from overwriting files. You can turn these features on and off like a toggle, using the set command. The set command takes two arguments: an option specifying on or off and the name of the feature. To set a feature on, you use the -o option, and to set it off, you use the +o option. Here is the basic form:

$ set -o feature turn the feature on
$ set +o feature turn the feature off

Features

Description

$ set -+o feature

BASH shell features are turned on and off with the set command; -o sets a feature on and +o turns it off:
$ set -o noclobber set noclobber on
$ set +o noclobber set noclobber off

ignoreeof

Disables CTRL-D logout

noclobber

Does not overwrite files through redirection

noglob

Disables special characters used for filename expansion: *, ?, ~, and []

Table 22-3: BASH Shell Special Features

Three of the most common features are ignoreeof, noclobber, and noglob. Table 22-3 lists these different features, as well as the set command. Setting ignoreeof enables a feature that prevents you from logging out of the user shell with CTRL-D. CTRL-D is not only used to log out of the user shell, but also to end user input entered directly into the standard input. CTRL-D is used often for the Mail program or for utilities such as cat. You can easily enter an extra CTRL-D in such circumstances and accidentally log yourself out. The ignoreeof feature prevents such accidental logouts. In the next example, the ignoreeof feature is turned on using the set command with the -o option. The user can then log out only by entering the logout command.

$ set -o ignoreeof
$ CTRL-D
Use exit to logout
$

Environment Variables and Subshells: export

When you log in to your account, Linux generates your user shell. Within this shell, you can issue commands and declare variables. You can also create and execute shell scripts. When you execute a shell script, however, the system generates a subshell. You then have two shells: the one you logged in to and the one generated for the script. Within the script shell, you can execute another shell script, which then has its own shell. When a script has finished execution, its shell terminates and you return to the shell from which it was executed. In this sense, you can have many shells, each nested within the other. Variables you define within a shell are local to it. If you define a variable in a shell script, then, when the script is run, the variable is defined with that script’s shell and is local to it. No other shell can reference that variable. In a sense, the variable is hidden within its shell.

Shell Variables

Description

BASH

Holds full pathname of BASH command

BASH_VERSION

Displays the current BASH version number

GROUPS

Groups that the user belongs to

HISTCMD

Number of the current command in the history list

HOME

Pathname for user’s home directory

HOSTNAME

The hostname

HOSTTYPE

Displays the type of machine the host runs on

OLDPWD

Previous working directory

OSTYPE

Operating system in use

PATH

List of pathnames for directories searched for executable commands

PPID

Process ID for shell's parent shell

PWD

User's working directory

RANDOM

Generates random number when referenced

SHLVL

Current shell level, number of shells invoked

UID

User ID of the current user

Table 22-4: Shell Variables, Set by the Shell

You can define environment variables in all types of shells, including the BASH shell, the Z shell, and the TCSH shell. The strategy used to implement environment variables in the BASH shell, however, is different from that of the TCSH shell. In the BASH shell, environment variables are exported. That is to say, a copy of an environment variable is made in each subshell. For example, if the EDITOR variable is exported, a copy is automatically defined in each subshell for you. In the TCSH shell, on the other hand, an environment variable is defined only once and can be directly referenced by any subshell.

In the BASH shell, an environment variable can be thought of as a regular variable with added capabilities. To make an environment variable, you apply the export command to a variable you have already defined. The export command instructs the system to define a copy of that variable for each new shell generated. Each new shell will have its own copy of the environment variable. This process is called exporting variables. To think of exported environment variables as global variables is a mistake. A new shell can never reference a variable outside of itself. Instead, a copy of the variable with its value is generated for the new shell.

Configuring Your Shell with Shell Parameters

When you log in, Linux will set certain parameters for your login shell. These parameters can take the form of variables or features. See the previous section “Controlling Shell Operations” for a description of how to set features. Linux reserves a predefined set of variables for shell and system use. These are assigned system values, in effect, setting parameters. Linux sets up parameter shell variables you can use to configure your user shell. Many of these parameter shell variables are defined by the system when you log in. Some parameter shell variables are set by the shell automatically, and others are set by initialization scripts, described later. Certain shell variables are set directly by the shell, and others are simply used by it. Many of these other variables are application specific, used for such tasks as mail, history, or editing. Functionally, it may be better to think of these as system-level variables, as they are used to configure your entire system, setting values such as the location of executable commands on your system, or the number of history commands allowable. See Table 22-4 for a list of those shell variables set by the shell for shell-specific tasks; Table 22-5 lists those used by the shell for supporting other applications.

A reserved set of keywords is used for the names of these system variables. You should not use these keywords as the names of any of your own variable names. The system shell variables are all specified in uppercase letters, making them easy to identify. Shell feature variables are in lowercase letters. For example, the keyword HOME is used by the system to define the HOME variable. HOME is a special environment variable that holds the pathname of the user’s home directory. On the other hand, the keyword noclobber is used to set the noclobber feature on or off.

Shell Parameter Variables

Many of the shell parameter variables automatically defined and assigned initial values by the system when you log in can be changed, if you wish. However, some parameter variables exist whose values should not be changed. For example, the HOME variable holds the pathname for your home directory. Commands such as cd reference the pathname in the HOME shell variable to locate your home directory. Some of the more common of these parameter variables are described in this section.

Other parameter variables are defined by the system and given an initial value that you are free to change. To do this, you redefine them and assign a new value. For example, the PATH variable is defined by the system and given an initial value; it contains the pathnames of directories where commands are located. Whenever you execute a command, the shell searches for it in these directories. You can add a new directory to be searched by redefining the PATH variable yourself, so that it will include the new directory’s pathname.

Still other parameter variables exist that the system does not define. These are usually optional features, such as the EXINIT variable that enables you to set options for the Vi editor. Each time you log in, you must define and assign a value to such variables. Some of the more common parameter variables are SHELL, PATH, PS1, PS2, and MAIL. The SHELL variable holds the pathname of the program for the type of shell you log in to. The PATH variable lists the different directories to be searched for a Linux command. The PS1 and PS2 variables hold the prompt symbols. The MAIL variable holds the pathname of your mailbox file. You can modify the values for any of these to customize your shell.

Note: You can obtain a listing of the currently defined shell variables using the env command. The env command operates like the set command, but it lists only parameter variables.

Using Initialization Files

You can automatically define parameter variables using special shell scripts called initialization files. An initialization file is a specially named shell script executed whenever you enter a certain shell. You can edit the initialization file and place in it definitions and assignments for parameter variables. When you enter the shell, the initialization file will execute these definitions and assignments, effectively initializing parameter variables with your own values. For example, the BASH shell’s .profile file is an initialization file executed every time you log in. It contains definitions and assignments of parameter variables. However, the .profile file is basically only a shell script, which you can edit with any text editor such as the Vi editor; changing, if you wish, the values assigned to parameter variables.

In the BASH shell, all the parameter variables are designed to be environment variables. When you define or redefine a parameter variable, you also need to export it to make it an environment variable. This means any change you make to a parameter variable must be accompanied by an export command. You will see that at the end of the login initialization file, .profile, there is usually an export command for all the parameter variables defined in it.

Your Home Directory: HOME

The HOME variable contains the pathname of your home directory. Your home directory is determined by the parameter administrator when your account is created. The pathname for your home directory is automatically read into your HOME variable when you log in. In the next example, the echo command displays the contents of the HOME variable:

$ echo $HOME
/home/chris

The HOME variable is often used when you need to specify the absolute pathname of your home directory. In the next example, the absolute pathname of reports is specified using HOME for the home directory’s path:

$ ls $HOME/reports

Command Locations: PATH

The PATH variable contains a series of directory paths separated by colons. Each time a command is executed, the paths listed in the PATH variable are searched, one by one, for that command. For example, the cp command resides on the system in the directory /bin. This directory path is one of the directories listed in the PATH variable. Each time you execute the cp command, this path is searched and the cp command located. The system defines and assigns PATH an initial set of pathnames. In Linux, the initial pathnames are /bin and /usr/bin.

Shell Variables

Description

BASH_VERSION

Displays the current BASH version number

CDPATH

Search path for the cd command

EXINIT

Initialization commands for Ex/Vi editor

FCEDIT

Editor used by the history fc command.

GROUPS

Groups that the user belongs to

HISTFILE

The pathname of the history file

HISTSIZE

Number of commands allowed for history

HISTFILESIZE

Size of the history file in lines

HOME

Pathname for user’s home directory

IFS

Interfield delimiter symbol

IGNOREEOF

If not set, EOF character will close the shell. Can be set to the number of EOF characters to ignore before accepting one to close the shell (default is 10)

INPUTRC

Set the inputrc configuration file for Readline (command line). Default is current directory, .inputrc. Most Linux distributions set this to /etc/inputrc

KDEDIR

The pathname location for the KDE desktop

LOGNAME

Login name

MAIL

Name of specific mail file checked by Mail utility for received messages, if MAILPATH is not set

MAILCHECK

Interval for checking for received mail

MAILPATH

List of mail files to be checked by Mail for received messages

HOSTTYPE

Linux platforms, such as i686, x86_64, or ppc

PROMPT_COMMAND

Command to be executed before each prompt.

HISTFILE

The pathname of the history file

PS1

Primary shell prompt

PS2

Secondary shell prompt

SHELL

Pathname of program for type of shell you are using

TERM

Terminal type

TMOUT

Time that the shell remains active awaiting input

USER

Username

UID

Real user ID (numeric)

Table 22-5: System Environment Variables Used by the Shell

The shell can execute any executable file, including programs and scripts you have created. For this reason, the PATH variable can also reference your working directory; so, if you want to execute one of your own scripts or programs in your working directory, the shell can locate it. No spaces are allowed between the pathnames in the string. A colon with no pathname specified references your working directory. Usually, a single colon is placed at the end of the pathnames as an empty entry specifying your working directory. For example, the pathname //bin:/usr/bin:references three directories: /bin, /usr/bin, and your current working directory.

$ echo $PATH
/bin:/usr/sbin:

You can add any new directory path you want to the PATH variable. This can be useful if you have created several of your own Linux commands using shell scripts. You can place these new shell script commands in a directory you create, and then add that directory to the PATH list. Then, no matter what directory you are in, you can execute one of your shell scripts. The PATH variable will contain the directory for that script, so that directory will be searched each time you issue a command.

You add a directory to the PATH variable with a variable assignment. You can execute this assignment directly in your shell. In the next example, the user chris adds a new directory, called bin, to the PATH. Although you could carefully type in the complete pathnames listed in PATH for the assignment, you can also use an evaluation of PATH—$PATH—in its place. In this example, an evaluation of HOME is also used to designate the user’s home directory in the new directory’s pathname. Notice the last colon, which specifies the working directory:

$ PATH=$PATH:$HOME/mybin:
$ export PATH
$ echo $PATH
/bin:/usr/bin::/home/chris/mybin

If you add a directory to PATH yourself while you are logged in, the directory will be added only for the duration of your login session. When you log back in, the login initialization file, .profile, will again initialize your PATH with its original set of directories. The .profile file is described in detail a bit later in this chapter. To add a new directory to your PATH permanently, you need to edit your .profile file and find the assignment for the PATH variable. Then, you simply insert the directory, preceded by a colon, into the set of pathnames assigned to PATH.

Specifying the BASH Environment: BASH_ENV

The BASH_ENV variable holds the name of the BASH shell initialization file to be executed whenever a BASH shell is generated. For example, when a BASH shell script is executed, the BASH_ENV variable is checked, and the name of the script that it holds is executed before the shell script. The BASH_ENV variable usually holds $HOME/.bashrc. This is the .bashrc file in the user’s home directory. (The .bashrc file is discussed later in this chapter.) You can specify a different file if you wish, using that instead of the .bashrc file for BASH shell scripts.

Configuring the Shell Prompt

The PS1 and PS2 variables contain the primary and secondary prompt symbols, respectively. The primary prompt symbol for the BASH shell is a dollar sign ($). You can change the prompt symbol by assigning a new set of characters to the PS1 variable. In the next example, the shell prompt is changed to the -> symbol:

$ PS1='->'
-> export PS1
->

The following table lists the codes for configuring your prompt:

Prompt Codes

Description

\!

Current history number

\$

Use $ as prompt for all users except the root user, which has the # as its prompt

\d

Current date

\#

History command number for just the current shell

\h

Hostname

\s

Shell type currently active

\t

Time of day in hours, minutes, and seconds.

\u

Username

\v

Shell version

\w

Full pathname of the current working directory

\W

Name of the current working directory

\\

Displays a backslash character

\n

Inserts a newline

\[ \]

Allows entry of terminal specific display characters for features like color or bold font

\nnn

Character specified in octal format

You can change the prompt to be any set of characters, including a string, as shown in the next example:

$ PS1="Please enter a command: "
Please enter a command: export PS1
Please enter a command: ls
mydata /reports
Please enter a command:

The PS2 variable holds the secondary prompt symbol, which is used for commands that take several lines to complete. The default secondary prompt is >. The added command lines begin with the secondary prompt instead of the primary prompt. You can change the secondary prompt just as easily as the primary prompt, as shown here:

$ PS2="@"

Like the TCSH shell, the BASH shell provides you with a predefined set of codes you can use to configure your prompt. With them you can make the time, your username, or your directory pathname a part of your prompt. You can even have your prompt display the history event number of the current command you are about to enter. Each code is preceded by a \ symbol: \w represents the current working directory, \t the time, and \u your username; \! will display the next history event number. In the next example, the user adds the current working directory to the prompt:

$ PS1="\w $"
/home/dylan $

The codes must be included within a quoted string. If no quotes exist, the code characters are not evaluated and are themselves used as the prompt. PS1=\w sets the prompt to the characters \w, not the working directory. The next example incorporates both the time and the history event number with a new prompt:

$ PS1="\t \! ->"

The default BASH prompt is \s-\v\$ to display the type of shell, the shell version, and the $ symbol as the prompt. Some distributions have changed this to a more complex command consisting of the user name, the hostname, and the name of the current working directory. A sample configuration is shown here. A simple equivalent is shown here with @ sign in the hostname and a $ for the final prompt symbol. The home directory is represented with a tilde (~).

$ PS1="\u@\h:\w$"
richard@turtle.com:~$

Ubuntu also includes some complex prompt definitions in the .bashrc file to support color prompts and detect any remote user logins.

Specifying Your News Server

Several shell parameter variables are used to set values used by network applications, such as web browsers or newsreaders. NNTPSERVER is used to set the value of a remote news server accessible on your network. If you are using an ISP, the ISP usually provides a Usenet news server you can access with your newsreader applications. However, you first have to provide your newsreaders with the Internet address of the news server. This is the role of the NNTPSERVER variable. News servers on the Internet usually use the NNTP protocol. NNTPSERVER should hold the address of such a news server. For many ISPs, the news server address is a domain name that begins with nntp. The following example assigns the news server address nntp.myservice.com to the NNTPSERVER shell variable. Newsreader applications automatically obtain the news server address from NNTPSERVER. Usually, this assignment is placed in the shell initialization file, .profile, so that it is automatically set each time a user logs in.

NNTPSERVER=news.myservice.com
export NNTPSERVER

Configuring Your Login Shell: .profile

The .profile file is the BASH shell’s login initialization file. It is a script file that is automatically executed whenever a user logs in. The file contains shell commands that define system environment variables used to manage your shell. They may be either redefinitions of system-defined variables, or definitions of user-defined variables. For example, when you log in, your user shell needs to know what directories hold Linux commands. It will reference the PATH variable to find the pathnames for these directories. However, first, the PATH variable must be assigned those pathnames. In the .profile file, an assignment operation does just this. Because it is in the .profile file, the assignment is executed automatically when the user logs in.

.profile

# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi

Exporting Variables

Any new parameter variables you may add to the .profile file, will also need to be exported, using the export command. This makes them accessible to any subshells you may enter. You can export several variables in one export command by listing them as arguments. The .profile file contain no variable definitions, though you can add ones of your own. In this case, the .profile file would have an export command with a list of all the variables defined in the file. If a variable is missing from this list, you may be unable to access it. The .bashrc file contain a definition of the HISTCONTROL variable, which is then exported. You can also combine the assignment and export command into one operation as shown here for NNTPSERVER:

export NNTPSERVER=news.myservice.com

Variable Assignments

A copy of the standard .profile file, provided for you when your account is created, is listed in the next example. Notice how PATH is assigned. PATH is a parameter variable the system has already defined. PATH holds the pathnames of directories searched for any command you enter. The assignment PATH="$PATH:$HOME/bin" has the effect of redefining PATH to include your bin directory within your home directory so that your bin directory will also be searched for any commands, including ones you create yourself, such as scripts or programs.

Should you want to have your current working directory searched also, you can use any text editor to add another PATH line in your .profile file PATH="$PATH:". You would insert a colon : after PATH. In fact, you can change this entry to add as many directories as you want to search. Making commands automatically executable in your current working directory could be a security risk, allowing files in any directory to be executed, instead of in certain specified directories. An example of how to modify your .profile file is shown in the following section.

PATH="$PATH:"

Editing Your BASH Profile Script

Your .profile initialization file is a text file that can be edited by a text editor, like any other text file. You can easily add new directories to your PATH by editing .profile and using editing commands to insert a new directory pathname in the list of directory pathnames assigned to the PATH variable. You can even add new variable definitions. If you do so, however, be sure to include the new variable’s name in the export command’s argument list. For example, if your .profile file does not have any definition of the EXINIT variable, you can edit the file and add a new line that assigns a value to EXINIT. The definition EXINIT='set nu ai' will configure the Vi editor with line numbering and indentation. You then need to add EXINIT to the export command’s argument list. When the .profile file executes again, the EXINIT variable will be set to the command set nu ai. When the Vi editor is invoked, the command in the EXINIT variable will be executed, setting the line number and auto-indent options automatically.

.profile

# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi

HISTSIZE=30
NNTPSERVER=news.myserver.com
EXINIT='set nu ai'
PS1="\w \$"
export PATH HISTSIZE EXINIT PS1 NNTPSERVER

In the following example, the user’s .profile has been modified to include definitions of EXINIT and redefinitions of PATH, PS1, and HISTSIZE. The PATH variable has the ending colon added to it that specifies the current working directory, enabling you to execute commands that may be located in either the home directory or the working directory. The redefinition of HISTSIZE reduces the number of history events saved, from 1,000 defined in the system’s .profile file, to 30. The redefinition of the PS1 parameter variable changes the prompt to just show the pathname of the current working directory. Any changes you make to parameter variables within your .profile file override those made earlier by the system’s .profile file. All these parameter variables are then exported with the export command.

Manually Re-executing the .profile script

Although the .profile script is executed each time you log in, it is not automatically re-executed after you make changes to it. The .profile script is an initialization file that is executed only whenever you log in. If you want to take advantage of any changes you make to it without having to log out and log in again, you can re-execute the .profile script with the dot (.) command. The .profile script is a shell script and, like any shell script, can be executed with the . command.

$ . .profile

Alternatively, you can use the source command to execute the .profile initialization file or any initialization file such as .login used in the TCSH shell or .bashrc.

$ source .profile

System Shell Profile Script

Your Linux system also has its own profile file that it executes whenever any user logs in. This system initialization file is simply called profile and is found in the /etc directory, /etc/profile. This file contains parameter variable definitions the system needs to provide for each user. On Ubuntu, the /etc/profile script checks the /etc/profile.d directory for any shell configuration scripts to run, and then runs the /etc/bash.baschrc script, which performs most of the configuration tasks.

The number of configuration settings needed for different applications would make the /etc/profile file much too large to manage. Instead, application task-specific aliases and variables are placed in separate configuration files located in the /etc/profile.d directory. There are corresponding scripts for both the BASH and C shells. The BASH shell scripts are run from /etc/profile with the following commands. A for loop sequentially accesses each script and executes it with the dot (.) operator.

for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done

For a basic install, you will have only the gvfs-bash-completion.sh script. As you install other shells and application there may be more. The /etc/profile.d scripts are named for the kinds of tasks and applications they configure. Files run by the BASH shell end in the extension .sh, and those run by the C shell have the extension .csh. The /etc/profile script will also check first if the PS1 variable is defined before running any /etc/profile.d scripts.

A copy of part of the system’s profile file follows

/etc/profile

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$PS1" ]; then
if [ "$BASH" ] && [ "$BASH != "/bin/sh" ]; then
PS1='\u@\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "`id -u`" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi

# The default umask is now handled by pam_umask.
# See pam_umask(8) and /etc/login.defs.

if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi

Configuring the BASH Shell: .bashrc

The .bashrc script is a configuration file executed each time you enter the BASH shell or generate any subshells. If the BASH shell is your login shell, .bashrc is executed along with your .profile script when you log in. If you enter the BASH shell from another shell, the .bashrc script is automatically executed, and the variable and alias definitions it contains will be defined. If you enter a different type of shell, the configuration file for that shell will be executed instead. For example, if you were to enter the TCSH shell with the tcsh command, the .tcshrc configuration file would be executed instead of .bashrc.

The User .bashrc BASH Script

The .bashrc shell configuration file is actually executed each time you generate a BASH shell, such as when you run a shell script. In other words, each time a subshell is created, the .bashrc file is executed. This has the effect of exporting any local variables or aliases you have defined in the .bashrc shell initialization file. The .bashrc file usually contains the definition of aliases and any feature variables used to turn on shell features. Aliases and feature variables are locally defined within the shell. But the .bashrc file defines them in every shell. For this reason, the.bashrc file usually holds aliases and options you want defined for each shell. As an example of how you can add your own aliases and options, aliases for the rm, cp, and mv commands and the shell noclobber and ignoreeof options have been added to the example shown here. For the root user .bashrc, the rm, cp, and mv aliases have already been included in the root’s .bashrc file.

The .bashrc file will check for aliases in a .bash_aliases file and run /etc/bash_completion for command completion directives.

The .bashrc file will set several features including history, prompt, alias, and command completion settings. The HISTCONTROL directive is defined to ignore duplicate commands and lines beginning with a space (ignoreboth). The history file is appended to, and the history size and history file sizes are set to 1000 and 2000.

# don't put duplicate lines or lines starting with space in the history
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1
HISTSIZE=1000
HISTFILESIZE=2000

Several commands then define terminal display features and command operations, including the shell prompt, beginning with PS1=.

The code for reading the user’s .bash_aliases script is included. Possible aliases are also provided, some of which are commented. You can remove the comment symbols, #, to activate them. Aliases that provide color support for the ls, grep, fgrep, and egrep commands are listed. An alert alias is also provided which notifies you of long running commands.

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi

# some more ls aliases
#alias ll='ls -alF'
#alias la='ls -A'
#alias l='ls -CF'

# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 && echo terminal || echo error)" "$(history | tial -n1 | sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

#if [ -f ~/.bash_aliases ]; then
# . ~/.bash_aliases
#fi

The .bash_completion file is then read to set up command completion options:

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi

You can add any commands or definitions of your own to your .bashrc file. If you have made changes to .bashrc and you want them to take effect during your current login session, you need to re-execute the file with either the . or the source command:

$ . .bashrc

The System /etc/bash.bashrc BASH Script

Ubuntu also has a system bashrc file executed for all users, called bash.bashrc. Currently the /etc/bash.bashrc file sets the default shell prompt, updates the window size, identifies the root directory, and checks whether a user is authorized to use a command. The bash.bashrc file is shown here:

# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

# sudo hint
if [ ! -e $HOME/.sudo_as_admin_successful ] && [ ! -e "$HOME/.hushlogin" ]; then
case " $(groups) " in *\ admin\ *)
if [ -x /usr/bin/sudo ]; then
cat <<-EOF
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

EOF
fi
esac
fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
function command_not_found_handle {
# check because c-n-f could've been removed in the meantime
if [ -x /usr/lib/command-not-found ]; then
/usr/bin/python /usr/lib/command-not-found -- "$1"
return $?
elif [ -x /usr/share/command-not-found/command-not-found ]; then
/usr/bin/python /usr/share/command-not-found/command-not-found -- "$1"
return $?
else
printf "%s: command not found\n" "$1" >&2
return 127
fi
}
fi

Though commented out, the file also includes statements to set the title of a terminal window to the user, hostname, and directory, as well as to enable bash completion.

The BASH Shell Logout File: .bash_logout

The .bash_logout file is also a configuration file, but it is executed when the user logs out. It is designed to perform any operations you want to occur whenever you log out. Instead of variable definitions, the .bash_logout file usually contains shell commands that form a kind of shutdown procedure—actions you always want taken before you log out. One common logout command is to clear the screen and then issue a farewell message.

As with .profile, you can add your own shell commands to .bash_logout. In fact, the .bash_logout file is not automatically set up for you when your account is first created. You need to create it yourself, using the Vi or Emacs editor. You could then add a farewell message or other operations. The default .bash_logout file includes instructions to invoke the clear_console command to clear the screen.

.bash_logout

# ~/.bash_logout: executed by bash(1) when login shell exits.
# when leaving the console clear the screen to increase privacy

if [ "$SHLVL" = 1 ]; then
[ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q
fi