13.2. The Environment

 <  Day Day Up  >  

The environment of a process consists of variables , open files, the current working directory, functions, resource limits, signals, and so forth. It defines those features that are inherited from one shell to the next and the configuration for the working environment. The configuration for the user 's shell is defined in the shell initialization files.

13.2.1 The Initialization Files

The bash shell has a number of startup files that are sourced. Sourcing a file causes all settings in the file to become part of the current shell; that is, a subshell is not created. (The source command is discussed in "The source or dot Command" on page 773.) The initialization files are sourced depending on the whether the shell is a login shell, an interactive shell (but not the login shell), or a noninteractive shell (a shell script).

When you log on, the .bash_profile in the user's home directory is sourced. It sets the user's aliases and functions and then sets user-specific environment variables and startup scripts.

If the user doesn't have a .bash_profile , but does have a file called .bash_login , that file will be sourced, and if he doesn't have a .bash_login , but does have a .profile , it will be sourced.

The /etc/profile File

The /etc/profile file is a systemwide initialization file set up by the system administrator to perform tasks when the user logs on. It is executed when bash starts up. It is also available to all Bourne and Korn shell users on the system and normally performs such tasks as checking the mail spooler for new mail and displaying the message of the day from the /etc/motd file. (The following examples will make more sense after you have completed this chapter.)

Example 13.4.
 (Sample /etc/profile)  # /etc/profile   # Systemwide environment and startup programs   # Functions and aliases go in /etc/bashrc  1   PATH="$PATH:/usr/X11R6/bin" 2   PS1="[\u@\h \W]\$ " 3   ulimit -c 1000000 4   if [ `id -gn` = `id -un` -a `id -u` -gt 14 ]; then 5       umask 002     else         umask 022     fi 6   USER=`id -un` 7   LOGNAME=$USER 8   MAIL="/var/spool/mail/$USER" 9   HOSTNAME=`/bin/hostname` 10  HISTSIZE=1000 11  HISTFILESIZE=1000 12  export PATH PS1 HOSTNAME HISTSIZE HISTFILESIZE USER LOGNAME MAIL 13  for i in /etc/profile.d/*.sh ; do 14      if [ -x $i ]; then 15           . $i         fi 16  done 17  unset i # 

EXPLANATION

  1. The PATH variable is assigned locations where the shell should search for commands.

  2. The primary prompt is assigned. It will be displayed in the shell window as the user's name ( \u ), the @ symbol, the host machine ( \W ), and a dollar sign.

  3. The ulimit command (a shell built-in command) is set to limit the maximum size of core files created to 1,000,000 bytes. Core files are memory dumps of programs that have crashed, and they take up a lot of disk space.

  4. This line reads: If the user's group name is equal to the user's name and the user's ID number is greater than 14 . . . (see line 5)

  5. . . . then set the umask to 002 . When directories are created they will get 775 permissions and files will get 664 permissions. Otherwise , the umask is set to 022 , giving 755 to directories and 644 to files.

  6. The USER variable is assigned the username ( id “un ).

  7. The LOGNAME variable is set to the value in $USER .

  8. The MAIL variable is assigned the path to the mail spooler where the user's mail is saved.

  9. The HOSTNAME variable is assigned the name of the user's host machine.

  10. The HISTSIZE variable is set to 1000 . HISTSIZE controls the number of history items that are remembered (from the history list stored in the shell's memory) and saved in the history file after the shell exits.

  11. The HISTFILESIZE is set to limit the number of commands stored in the history file to 1000 , that is, the history file is truncated after it reaches 1,000 lines. (See "History" on page 785.)

  12. These variables are exported so that they will be available in subshells and child processes.

  13. For each file (ending in .sh ) in the etc/profile.d directory . . . (see line 14)

  14. . . . check to see if the file is executable, and if it is . . . (see line 15)

  15. . . . execute (source) the file with the dot command. The files in the /etc/profile.d directory ( lang.sh and mc.sh , respectively) set the character and font sets and create a function called mc that starts up a visual/browser file manager program called Midnight Commander . To see how the file manager works, type mc at the bash prompt.

  16. The done keyword marks the end of the for loop.

  17. The variable i is unset , that is, removed from shell's name space. The value of i is whatever was assigned to it while in the for loop, if anything was assigned at all.

The ~/.bash_profile File

If the ~/.bash_profile is found in the user's home directory, it is sourced after the /etc/profile . If ~/.bash_profile doesn't exist, bash will look for another user-defined file, ~./bash_login , and source it, and if ~./bash_login doesn't exist, it will source the ~/.profile , if it exists. Only one of the three files ( ~/.bash_profile , ~/.bash_login , or ~/.profile ) will be sourced. Bash will also check to see if the user has a .bashrc file and then source it.

Example 13.5.
 (Sample .bash_profile)  # .bash_profile   # The file is sourced by bash only when the user logs on.   # Get the aliases and functions  1   if [ -f ~/.bashrc ]; then 2       . ~/.bashrc     fi  # User-specific environment and startup programs  3   PATH=$PATH:$HOME/bin 4   ENV=$HOME/.bashrc  # or BASH_ENV=$HOME/.bashrc  5   USERNAME="root" 6   export USERNAME ENV PATH 7   mesg n 8   if [ $TERM = linux ]     then         startx  # Start the X Window system  fi 

EXPLANATION

  1. If there is a file called .bashrc in the user's home directory . . . (see line 2)

  2. . . . execute (source) the .bashrc file for the login shell.

  3. The PATH variable is appended with a path to the user's bin directory, normally the place where shell scripts are stored.

  4. The BASH_ENV [a] ( ENV ) file is set to the pathname for the .bashrc file, an initialization file that will be sourced for interactive bash shells and scripts only if the BASH_ENV ( ENV ) variable is set. The .bashrc file contains user-defined aliases and functions.

    [a] BASH_ENV is used by versions of bash starting at 2.0.

  5. The variable USERNAME is set to root .

  6. The variables are exported so that they are available to subshells, and other processes will know about them.

  7. The mesg command is executed with the n option, disallowing others to write to the terminal.

  8. If the value of the TERM variable is linux , then startx will start the X Window system (the graphical user interface allowing multiple virtual consoles), rather than starting an interactive session in the Linux console window. Because the ~/.bash_profile is only sourced when you log in, the login shell would be the best place to start up your X Windows session.

The BASH_ENV ( ENV ) Variable

Before bash version 2.0, the BASH_ENV file was simply called the ENV file (same as in Korn shell). The BASH_ENV ( ENV ) variable is set in the ~/.bash_profile . It is assigned the name of a file that will be executed every time an interactive bash shell or bash script is started. The BASH_ENV ( ENV ) file will contain special bash variables and aliases. The name is conventionally .bashrc , but you can call it anything you want. The BASH_ENV ( ENV ) file is not processed when the privileged option is on ( bash “p or set “o privileged ) or the “ “norc command-line option is used ( bash “norc or bash “ “norc if using bash 2.x+).

The .bashrc File

The BASH_ENV ( ENV ) variable is assigned (by convention) the name .bashrc . This file is automatically sourced every time a new or interactive bash shell or bash script starts. It contains settings that pertain only to the bash shell.

Example 13.6.
 (Sample .bashrc)  # If the .bashrc file exists, it is in the user's home directory.   # It contains aliases (nicknames for commands) and user-defined functions.   # .bashrc   # User-specific aliases and functions  1   set -o vi 2   set -o noclobber 3   set -o ignoreeof 4   alias rm='rm -i'     alias cp='cp -i'     alias mv='mv -i' 5   stty erase ^h  # Source global definitions  6   if [ -f /etc/bashrc ]; then         . /etc/bashrc     fi 7   case "$-" in 8       *i*) echo This is an interactive bash shell             ;; 9       *)   echo This shell is noninteractive              ;;     esac 10  history_control=ignoredups 11  function cd { builtin cd ; echo $PWD; } 

EXPLANATION

  1. The set command with the “o switch turns on or off special built-in options. (See "The set “o Options" on page 763.) If the switch is “o , a minus sign, the option is turned on, and if a plus sign, the option is turned off. The vi option allows interactive command-line editing. For example, set “o vi turns on interactive command-line editing, whereas set vi +o turns it off. (See Table 13.1 on page 764.)

    Table 13.1. The Built-In set Command Options

    Name of Option

    Shortcut Switch

    What It Does

    allexport

    “a

    Automatically marks new or modified variables for export from the time the option is set, until unset.

    braceexpand

    “B

    Enables brace expansion, and is a default setting.

    emacs

     

    For command-line editing, uses the emacs built-in editor, and is a default setting.

    errexit

    “e

    If a command returns a nonzero exit status (fails), exits. Not set when reading initialization files.

    histexpand

    “H

    Enables ! and !! when performing history substitution, and is a default setting.

    history

     

    Enables command-line history; on by default.

    ignoreeof

     

    Disables EOF (Ctrl-D) from exiting a shell; must type exit . Same as setting shell variable IGNOREEOF=10 .

    keyword

    “k

    Places keyword arguments in the environment for a command.

    interactive-comments

     

    For interactive shells, a leading # is used to comment out any text remaining on the line.

    monitor

    “m

    Allows job control.

    noclobber

    “C

    Protects files from being overwritten when redirection is used.

    noexec

    “n

    Reads commands, but does not execute them. Used to check the syntax of scripts. Not on when running interactively.

    noglob

    “d

    Disables pathname expansion; that is, turns off wildcards.

    notify

    “b

    Notifies user when background job finishes.

    nounset

    “u

    Displays an error when expanding a variable that has not been set.

    onecmd

    “t

    Exits after reading and executing one command.

    physical

    “P

    If set, does not follow symbolic links when typing cd or pwd . The physical directory is used instead.

    posix

     

    Shell behavior is changed if the default operation doesn't match the POSIX standard.

    privileged

    “p

    When set, the shell does not read the .profile or ENV file and shell functions are not inherited from the environment; automatically set for setuid scripts.

    verbose

    “v

    Turns on the verbose mode for debugging.

    vi

     

    For command-line editing, uses the vi built-in editor.

    xtrace

    “x

    Turns on the echo mode for debugging.


  2. The noclobber option is turned on, which prevents the user from overwriting files when using redirection; for example, sort filex > filex . (See "Standard I/O and Redirection" on page 844.)

  3. When exiting a shell, normally you can type ^D (Ctrl-D). With ignoreeof set, you must type exit .

  4. The alias for rm , rm “i , causes rm to be interactive ( “i ), that is, it will ask the user if it's okay to remove files before actually removing them. The alias for the cp command, cp “i , causes the copy to be interactive.

  5. The stty command is used to set the terminal backspace key to erase. ^H represents the Backspace key.

  6. If a file called /etc/bashrc exists, source it.

  7. If the shell is interactive, the special variable, $ “ , will contain an i . If not, you are probably running a script. The case command evaluates $ “ .

  8. If the value returned from $ “ matches *i* (i.e., any string containing an i ), then the shell prints This is an interactive bash shell .

  9. Otherwise, the shell prints This shell is noninteractive . If you start up a script or a new shell at the prompt, you will be able to tell whether your shell is interactive. It is only here to let you test your understanding of the terms "interactive" and "noninteractive" shell.

  10. The history_control setting is used to control how commands are saved in the history file. This line reads: Don't save commands in the history file if they're already there; that is, ignore duplicates.

  11. This is a user-defined function. When the user changes directories, the present working directory, PWD , is printed. The function is named cd and contains within its definition the command cd . The special built-in command, called builtin , precedes the cd command within the function definition to prevent the function from going into an infinite recursion; that is, from calling itself indefinitely.

The /etc/bashrc File

Systemwide functions and aliases can be set in the /etc/bashrc file. The primary prompt is often set here.

Example 13.7.
 (Sample /etc/bashrc)  # Systemwide functions and aliases   # Environment stuff goes in /etc/profile   # For some unknown reason bash refuses to inherit   # PS1 in some circumstances that I can't figure out.   # Putting PS1 here ensures that it gets loaded every time.  1   PS1="[\u@\h \W]\$ " 2   alias which="type -path" 

EXPLANATION

  1. Systemwide functions and aliases are set here. The primary bash prompt is set to the name of the user (\u), and @ symbol, the host machine (\h), the basename of the current working directory, and a dollar sign. (See Table 13.2 on page 769.) This prompt will appear for all interactive shells.

    Table 13.2. Prompt String Settings

    Backslash Sequence

    What It Evaluates To

    \d

    The date in Weekday Month Date format (e.g., Tue May 26)

    \h

    The hostname

    \n

    Newline

    \nnn

    The character corresponding to the octal number nnn

    \s

    The name of the shell, the basename of $0 (the portion following the final slash)

    \t

    The current time in HH:MM:SS format

    \u

    The username of the current user

    \w

    The current working directory

    \W

    The basename of the current working directory

    \#

    The command number of this command

    \!

    The history number of this command

    \$

    If the effective UID is 0, a # , otherwise a $

    \\

    Backslash

    \[

    Begin a sequence of nonprinting characters ; could be used to embed a terminal control sequence into the prompt

    \]

    End a sequence of nonprinting characters

    New in bash 2.x+

    \a

    The ASCII bell character

    \e

    The ASCII escape character (033)

    \H

    The hostname

    \T

    The current time in 12- hour format: HH:MM:SS

    \v

    The version of bash , e.g., 2.03

    \V

    The release and pathlevel of bash ; e.g., 2.03.0

    \@

    The current time in 12-hour AM/PM format


  2. Aliases, nicknames for commands, are usually set in the user's .bashrc file. The alias was preset and is available when bash starts up. You use it when you want to find out where a program resides on disk; that is, what directory it is found in (e.g., which ls will print /bin/ls ).

The ~/.profile File

The .profile file is a user-defined initialization file. It is found in the user's home directory, and sourced once at login if running sh (Bourne shell). Because this file is used by the Bourne shell, it should not contain any bash -specific settings. If running bash , .profile will be run if bash cannot find any other of the initialization files listed previously. It allows a user to customize and modify his or her shell environment. Environment and terminal settings are normally put here, and if a window application or database application is to be initiated, it is started here.

Example 13.8.
 (Sample .profile)  # A login initialization file sourced when running as sh or the #.bash_profile or   # .bash_login are not found.  1   TERM=xterm 2   HOSTNAME=`uname -n` 3   EDITOR=/bin/vi 4   PATH=/bin:/usr/ucb:/usr/bin:/usr/local:/etc:/bin:/usr/bin:. 5   PS1="$HOSTNAME $ > " 6   export TERM HOSTNAME EDITOR PATH PS1 7   stty erase ^h 8   go () { cd ; PS1=`pwd`; PS1=`basename $PS1`; } 9   trap '$HOME/.logout' EXIT 10  clear 

EXPLANATION

  1. The TERM variable is assigned the value of the terminal type, xterm .

  2. Because the uname “n command is enclosed in backquotes, the shell will perform command substitution; that is, the output of the command (the name of the host machine) will be assigned to the variable HOSTNAME .

  3. The EDITOR variable is assigned /bin/vi . Programs such as mail and history will now have this variable available when defining an editor.

  4. The PATH variable is assigned the directory entries that the shell searches in order to find a UNIX/Linux program. If, for example, you type ls , the shell will search the PATH until it finds that program in one of the listed directories. If it never finds the program, the shell will tell you so.

  5. The primary prompt is assigned the value of HOSTNAME , the machine name, and the $ and > symbols.

  6. All of the variables listed are exported. They will be known by child processes started from this shell.

  7. The stty command sets terminal options. The Erase key is set to ^H, so that when you press the Backspace key, the letter typed preceding the cursor is erased.

  8. A function called go is defined. The purpose of this function is to take one argument, a directory name, then cd to that directory and set the primary prompt to the present working directory. The basename command removes all but the last entry of the path. The prompt will show you the current directory.

  9. The trap command is a signal-handling command. When you exit the shell, that is, log out, the .logout file will be executed. The .logout file is a user-defined file containing commands that will be executed just before logging out, commands that will clean up temp files, log the time of logout, and so forth.

  10. The clear command clears the screen.

The ~/.bash “logout File

When the user logs out (exits the login shell), if a file called ~/.bash_logout exists, it is sourced. This file normally contains commands to clean up temporary files, truncate the history file, record the time of logout, and perform other housekeeping tasks.

Options to Prevent Startup Files from Being Executed

If bash is invoked with the “ “noprofile option (for example, bash “ “noprofile ), then the /etc/profile , ~/.bash_profile , ~/.bash_login , or ~/.profile startup files will not be sourced.

If invoked with the “p option (e.g., bash “p ), bash will not read the user's ~/.profile file.

If bash is invoked as sh (Bourne shell), it tries to mimic the behavior of the Bourne shell as closely as possible. For a login shell, it attempts to source only /etc/profile and ~/.profile , in that order. The “noprofile option may still be used to disable this behavior. If the shell is invoked as sh , it does not attempt to source any other startup files.

The .inputrc File

Another default initalization file, .inputrc , is also read when bash starts up. This file, if it exists in the user's home directory, contains variables to customize keystroke behavior and settings that bind strings, macros, and control functions to keys. The names for the key bindings and what they do are found in the Readline library, a library that is used by applications that manipulate text. The bindings are used particularly by the built-in emacs and vi editors when performing command-line editing. (See "Command-Line Editing" on page 793 for more on readline .)

13.2.2 Setting bash Options with the Built-In set and shopt Commands

The set “o Options

The set command can take options when the “o switch is used. Options allow you to customize the shell environment. They are either on or off, and are normally set in the BASH_ENV ( ENV ) file. Many of the options for the set command are set with an abbreviated form. For example, set “o noclobber can also be written, set “C . (See Table 13.1.)

FORMAT

 set -o option  # Turns on the option.  set +o option  # Turns off the option.  set -[a-z]  # Abbreviation for an option; the minus turns it on.  set +[a-z]  # Abbreviation for an option; the plus turns it off.  

Example 13.9.
 1   set -o allexport 2   set +o allexport 3   set -a 4   set +a 

EXPLANATION

  1. Sets the allexport option. This option causes all variables to be automatically exported to subshells.

  2. Unsets the allexport option. All variables will now be local in the current shell.

  3. Sets the allexport option. Same as 1. Not every option has an abbreviation. (See Table 13.1.)

  4. Unsets the allexport option. Same as 2.

Example 13.10.
 1 $  set -o   braceexpand            on   errexit                off   hashall                on   histexpand             on   keyword                off   monitor                on   noclobber              off   noexec                 off   noglob                 off   notify                 off   nounset                off   onecmd                 off   physical               off   privileged             off   verbose                off   xtrace                 off   history                on   ignoreeof              off   interactive-comments   on   posix                  off   emacs                  off   vi                     on  2   $  set -o noclobber  3   $ date > outfile 4   $ ls > outfile  bash: outfile: Cannot clobber existing file.  5   $  set +o noclobber  6   $ ls > outfile 7   $  set -C  

EXPLANATION

  1. With the “o option, the set command lists all the options currently set or not set.

  2. To set an option, the “o option is used. The noclobber option is set. It protects you from overwriting files when using redirection. Without noclobber , the file to the right of the > symbol is truncated if it exists, and created if it doesn't exist.

  3. The output of the UNIX/Linux date command is redirected to a file called outfile .

  4. This time, the outfile exists. By attempting to redirect the output of ls to outfile , the shell complains that the file already exists. Without noclobber set, it would be clobbered.

  5. With the +o option to the set command, noclobber is turned off.

  6. This time, trying to overwrite outfile is fine because noclobber is no longer set.

  7. Using the “C switch to the set command is an alternate way of turning on noclobber . +C would turn it off.

The shopt Built-In (Version 2.x+)

The shopt ( shell options ) built-in command is used in newer versions of bash as an alternative to the set command. In many ways shopt duplicates the set built-in command, but it adds more options for configuring the shell. See Table 13.27 on page 855 for a list of all the shopt options. In the following example, shopt with the “p option prints all the available options settings. The “u switch indicates an unset option and “s indicates one that is currently set.

Example 13.11.
 1   $  shopt -p   shopt -u cdable_vars   shopt -u cdspell   shopt -u checkhash   shopt -u checkwinsize   shopt -s cmdhist   shopt -u dotglob   shopt -u execfail   shopt -s expand_aliases   shopt -u extglob   shopt -u histreedit   shopt -u histappend   shopt -u histverify   shopt -s hostcomplete   shopt -u huponexit   shopt -s interactive_comments   shopt -u lithist   shopt -u mailwarn   shopt -u nocaseglob   shopt -u nullglob   shopt -s promptvars   shopt -u restricted_shell   shopt -u shift_verbose   shopt -s sourcepath  2   $  shopt -s cdspell  3   $  shopt -p cdspell   shopt -s cdspell  4   $  cd /hame   /home  5   $  pwd   /home  6   $  cd /ur/lcal/ban   /usr/local/man  7   $  shopt -u cdspell  8   $  shopt -p cdspell   shopt -u cdspell  

Table 13.27. The shopt Command Options

Option

Meaning

cdable_vars

If an argument to the cd built-in command is not a directory, it is assumed to be the name of a variable whose value is the directory to change to.

cdspell

Corrects minor errors in the spelling of a directory name in a cd command. The errors checked for are transposed characters, a missing character, and a character too many. If a correction is found, the corrected path is printed, and the command proceeds. Only used by interactive shells.

checkhash

Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.

checkwinsize

Bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS .

cmdhist

Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multiline commands.

dotglob

Bash includes filenames beginning with a dot (.) in the results of filename expansion.

execfail

A noninteractive shell will not exit if it cannot execute the file specified as an argument to the exec built-in command. An interactive shell does not exit if exec fails.

expand_aliases

Aliases are expanded. Enabled by default.

extglob

The extended pattern-matching features (regular expression metacharacters derived from Korn shell for filename expansion) are enabled.

histappend

The history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.

histreedit

If readline is being used, a user is given the opportunity to re-edit a failed history substitution.

histverify

If set, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification.

hostcomplete

If set, and readline is being used, bash will attempt to perform hostname completion when a word containing @ is being completed. Enabled by default.

huponexit

If set, bash will send SIGHUP (hangup signal) to all jobs when an interactive login shell exits.

interactive_comments

Allows a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell. Enabled by default.

lithist

If enabled, and the cmdhist option is enabled, multiline commands are saved to the history with embedded newlines rather than using semicolon separators where possible.

mailwarn

If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message The mail in mailfile has been read is displayed.

nocaseglob

If set, bash matches filenames in a case-insensitive fashion when performing filename expansion.

nullglob

If set, bash allows filename patterns that match no files to expand to a null string, rather than themselves .

promptvars

If set, prompt strings undergo variable and parameter expansion after being expanded. Enabled by default.

restricted_shell

The shell sets this option if it is started in restricted mode. The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted.

shift_verbose

If this is set, the shift built-in prints an error message when the shift count exceeds the number of positional parameters.

sourcepath

If set, the source built-in uses the value of PATH to find the directory containing the file supplied as an argument. Enabled by default.

source

A synonym for dot (.).


EXPLANATION

  1. With the “p (print) option, the shopt command lists all settable shell options and their current values, either set ( “s ) or unset ( “u ).

  2. With the “s option, shopt sets (or turns on) an option. The cdspell option causes the shell to correct minor spelling errors on directory names given as arguments to the cd command. It will correct simple typos, insert missing letters, and even transpose letters if it can.

  3. With the “p option and the name of the option, shopt indicates whether the option is set. The option has been set ( “s ).

  4. In this example, the user tries to cd to his or her home directory, but misspells home . The shell fixes the spelling and hame becomes home . The directory is changed to /home .

  5. The output of the pwd command displays the current working directory, showing that the directory was really changed even though the user spelled it wrong.

  6. This time the directory name is missing letters and has a misspelling for the last entry , ban . The shell makes a pretty good attempt to spell out the correct pathname by inserting the missing letters, and correcting ban to man . Because the b in ban is the first misspelled character, the shell searches in the directory for an entry that might end with a and n . It finds man .

  7. With the “u switch, [a] shopt unsets (or turns off) the option.

    [a] The words switch and option are interchangeable. They are arguments to a command that contain a leading dash.

  8. With the “p switch and the name of the option, shopt indicates whether the option is set. The cdspell option has been unset ( “u ).

13.2.3 The Prompts

When used interactively, the shell prompts you for input. When you see the prompt, you know that you can start typing commands. The bash shell provides four prompts: the primary prompt is a dollar sign ( $ ); the secondary prompt is a right angle bracket symbol ( > ); the third and fourth prompts, PS3 and PS4 , respectively, will be discussed later. The prompts are displayed when the shell is running interactively. You can change these prompts.

The variable PS1 is set to a string containing the primary prompt. Its value, the dollar sign, appears when you log on and waits for user input, normally a UNIX/Linux command. The variable PS2 is the secondary prompt, initially set to the right angle bracket character ( > ). It appears if you have partially typed a command and then pressed Enter. You can change the primary and secondary prompts.

The Primary Prompt

The dollar sign (or bash $ ) is the default primary prompt. You can change your prompt. Normally, prompts are defined in /etc/bashrc or the user initialization file, .bash_profile , or .profile (Bourne shell).

Example 13.12.
 1   $  PS1="$(uname -n) > "  2  chargers >  

EXPLANATION

  1. The default primary prompt is a dollar sign ( bash $ ). The PS1 prompt is being reset to the name of the machine [a] ( uname “n ) and a > symbol.

    [a] The command, uname “n , is executed because it is enclosed in a set of parentheses preceded by a dollar sign. An alternative would be to enclose the command in backquotes. (See "Command Substitution" on page 835.)

  2. The new prompt is displayed.

Setting the Prompt with Special Escape Sequences

By inserting special backslash/escape sequences into the prompt string, you can customize the prompts. Table 13.2 lists the special sequences.

Example 13.13.
 1   $  PS1="[\u@\h \W]\$ "   [ellie@homebound ellie]$  2   $  PS1="\W:\d> "   ellie:Tue May 18>  

EXPLANATION

  1. You customize the primary bash prompt using special backslash/escape sequences. \u evaluates to the user's login name, \h to the host machine, and \W is the basename for the current working directory. There are two backslashes. The first backslash escapes the second backslash, resulting in \$ . The dollar sign is protected from shell interpretation and thus printed literally.

  2. The primary prompt is assigned \W , the escape sequence evaluating to the basename of the current working directory, and \d , the escape sequence evaluating to today's date.

The Secondary Prompt

The PS2 variable is assigned a string called the secondary prompt. Its value is displayed to standard error, which is the screen by default. This prompt appears when you have not completed a command or more input is expected. The default secondary prompt is > .

Example 13.14.
 1   $ echo "Hello 2  >  there" 3  Hello   there  4   $ 5   $  PS2="> "  6   $ echo 'Hi 7  >   >   >  there'  Hi   there  $ 8   $  PS2="\s:PS2 > "  $ echo 'Hello     bash:PS2 > what are     bash:PS2 > you     bash:PS2 > trying to do?     bash:PS2 > '  Hello   what are   you   trying to do?  $ 

EXPLANATION

  1. The double quotes must be matched after the string "Hello .

  2. When a newline is entered, the secondary prompt appears. Until the closing double quotes are entered, the secondary prompt will be displayed.

  3. The output of the echo command is displayed.

  4. The primary prompt is displayed.

  5. The secondary prompt is reset.

  6. The single quote must be matched after the string 'Hi .

  7. When a newline is entered, the new secondary prompt appears. Until the closing single quote is entered, the secondary prompt will be displayed.

  8. The PS2 prompt is set to the name of the shell ( \s ) followed by a string consisting of a colon , PS2 and > , followed by a space.

13.2.4 The Search Path

Bash uses the PATH variable to locate commands typed at the command line. The path is a colon-separated list of directories used by the shell when searching for commands. The default path is system-dependent, and is set by the administrator who installs bash . The path is searched from left to right. The dot at the end of the path represents the current working directory. If the command is not found in any of the directories listed in the path, the shell sends to standard error the message filename: not found. The path is normally set in the .bash_profile if running the bash shell or .profile file if using sh , the Bourne shell.

If the dot is not included in the path and you are executing a command or script from the current working directory, the name of the script must be preceded with a ./ , such as ./program_name , so that shell can find the program.

Example 13.15.
 (Printing the PATH) 1   $  echo $PATH   /usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin:.  (Setting the PATH) 2   $  PATH=$HOME:/usr/ucb:/usr:/usr/bin:/usr/local/bin:  3   $  export PATH  4   $  runit   bash: runit: command not found   5   $   ./runit  < program starts running here > 

EXPLANATION

  1. By echoing $PATH , the value of the PATH variable is displayed. The path consists of a list of colon-separated elements and is searched from left to right. The dot at the end of the path represents the user's current working directory.

  2. To set the path, a list of colon-separated directories are assigned to the PATH variable. Note that in this path, the dot is not at the end of the path, perhaps as a security measure.

  3. By exporting the path, child processes will have access to it. It is not necessary to export the PATH on a separate line: It could be written as follows :

    export PATH=$HOME:/usr/ucb:/bin:. , and so on, on the same line.

  4. Because the dot is not in the search path, when the runit program is executed in the present working directory, bash can't find it.

  5. Because the program name is preceded with a dot and a slash ( ./ ), the shell will be able to find it, and execute it, if it is the current working directory.

13.2.5 The hash Command

The hash command controls the internal hash table used by the shell to improve efficiency in searching for commands. Instead of searching the path each time a command is entered, the first time you type a command, the shell uses the search path to find the command, and then stores it in a table in the shell's memory. The next time you use the same command, the shell uses the hash table to find it. This makes it much faster to access a command than having to search the complete path. If you know that you will be using a command often, you can add the command to the hash table. You can also remove commands from the table. The output of the hash command displays the number of times the shell has used the table to find a command ( hits ) and the full pathname of the command. The hash command with the “r option clears the hash table. An argument of “ “ disables option checking for the rest of the arguments. Hashing is automatically implemented by bash . Although you can turn it off, if there isn't any compelling reason to do so, don't.

Example 13.16.
 (Printing the PATH) (Command line) 1  hash   hits    command   1       /usr/bin/mesg   4       /usr/bin/man   2       /bin/ls  2  hash -r  3  hash   No commands in hash table  4  hash find   hits    command   0       /usr/bin/find  

EXPLANATION

  1. The hash command displays the full pathname of commands that have been executed in this login session. (Built-in commands are not listed.) The number of hits is the number of times the hash table has been used to find the command.

  2. The “r option to the hash command erases all remembered locations in the hash table.

  3. After the “r option was used in the last command, the hash command reports that there are no commands currently in the table.

  4. If you know you are going to use a command often, you can add it to the hash table by giving it as an argument to the hash command. The find command has been added. The table has 0 hits because the command hasn't been used yet.

13.2.6 The source or dot Command

The source command (from the C shell) is a built-in bash command. The dot command, simply a period (from the Bourne shell), is another name for source . Both commands take a script name as an argument. The script will be executed in the environment of the current shell; that is, a child process will not be started. All variables set in the script will become part of the current shell's environment. Likewise, all variables set in the current shell will become part of the script's environment. The source (or dot ) command is normally used to re-execute any of the initialization files, such as .bash_profile , .profile , and so on, if they have been modified. For example, if one of the settings, such as the EDITOR or TERM variable, has been changed in the .bash_profile since you logged on, you can use the source command to re-execute commands in the .bash_profile without logging out and then logging back on. A file, such as .bash_profile , or for that matter any shell script, does not need execute permissions to be sourced with either the dot or the source commands.

Example 13.17.
 $  source .bash_profile  $  . .bash_profile  

EXPLANATION

The source or dot command executes the initialization file, .bash_profile , within the context of the current shell. Local and global variables are redefined within this shell. The dot command makes it unnecessary to log out and then log back in again after the file has been modified. [a]

[a] If the .bash_profile were executed directly as a script, a child shell would be started. Then the variables would be set in the child shell, and when the child shell exited, the parent shell would not have any of the settings available to it.

 <  Day Day Up  >  


UNIX Shells by Example
UNIX Shells by Example (4th Edition)
ISBN: 013147572X
EAN: 2147483647
Year: 2004
Pages: 454
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net