Untitled Document

Chapter - 16 Environment Setup

In Chapter - 8 we have discuss about SHELL and its function . Lets see some more details and history about it . The UNIX / Linux shell is both an interpreter and a scripting language . When we log in , an interactive program called shell runs at our terminal , presents a prompt and waits for your request . This shell is called an interactive shell , which supports job control , aliases and history . In this chapter we are more conerned about interactive shells .

The first UNIX shell was developed by Steve Bourne , the Shell was weak as an interpreter but had reasonably strong programming feature .The C shell was created by Bill Joy at Berkeley to improve intepretive features of Bourne . But Joy's shell wasn't suitable for programming .Things chnaged when David Korn developed the Korn Shell . It combine the best of both worlds - the interactive features of C shell and the programming feature of Bourne .Korn offered important features like aliases and command history and also offered additional programming features not available in Bourne .

Bash was developed by GNU as a Bourne - again shell . It was a grand superset combined with features of Korn and C shell .

 

Environment Variable - 

Shell varibales are of two types - Local and Environment . PATH, HOME and SHELL are environment variables . They are so called because they are available in the users total environment . The sub shells or commands like mail, vi etc use these variables .Local variables are more restricted in scope as shown by below example

DOWNLOAD_DIR=/home/mangesh/download

echo $DOWNLOAD_DIR

/home/mangesh/download

DOWNLOAD_DIR is a Local variable , its value is not available to child pocess. Run a Korn shell with ksh and check whether we can see the variable there .

ksh

The set statement displays all variables in the current shell , but the env command displays only environment variables .

env

By default , environment variable names are defined in uppercase though nothing prevents us from using different scheme. env is an external command and runs in a child process. It thus lists only those variables that it has inherited from its parent , the shell . But set is a shell built-in and shows all variables visible in the current shell . set will display the value of but not env .

Applications often obtain information on the process environment through these environment variables. vi reads TERM and mailx looks up MAIL .Applications are not designed to run from a specific shell , so environment varibales always present information in the name=value format . They may however , be assigned differently in the different shells .

A local variable can be converted to an environment variable using the shell's export statement .

Common Environment Variables -

Environment variables controls the behaviour of the system .They determine the environment in which you work . If they are not set properly , you may not be able to use some commands without a pathname. We can set or reset these variables to our likings . We have already seen some Environment variables like PATH , HOME , LOGNAME etc . Lets examine some variables specific to our shell .

The Command Search Path ( PATH ) - The PATH variable instructs the shell about the route it should follow to locate any executable command . Its current value is displayed by env shows a list of four directories . To include the directory /usr/docs/bin in our search list we will have to reassign this variable

PATH=$PATH:/usr/docs/bin

Home Directory ( HOME )

When a user log in UNIX / Linux normally places you in a directory name after your login name . The Directory is called the home or login directory and is available in the variable HOME .

echo $HOME

/home/mangesh

The home directory ( $HOME) for a user is set by the system administrator in /etc/passwd/ . The line for the user looks like this :

mangesh:x:1008:45::/home/mangesh/:/bin/ksh

The home directory is set in the last but one field . This file can be edited by the system administrator , wither manually or by invoking the useradd or usermod commands. You only have to tell the administrator if you desire a change of HOME .

Mailbox Location and Checking Mail ( MAIL and MAILCHECK) -

The UNIX mail handling system doesn't inform the user that mail has arrived ; that job is done by shell . It knows the location of user's mailbox from MAIL. This mailbox is generally /var/mail or var/spool/mail ( Linux ) . Mangesh's mail is saved in /var/mail/mangesh .

MAILCHECK determines how often the shell checks the file for the arrival of new mail . If the shell finds the file modified since the last check , it informs the user with this familiar message :

You have mail in /var/mail/mangesh

The Prompt Strings ( PS1 and PS2 )  

The shell has two prompts . The primary prompt string PS1 is the one we normally see . We have also seen when discussing the echo command , how a multiline command makes the shell respond with a > . The > is secondary prompt string stored in PS2 .Normally , PS1 and PS2 in the Bourne Shell are set to the characters $ and > , respectively .

You can change the primary prompt string to C> if you find the Windows environment more reassuming :

$ PS="C>"

C> _

While the $ is the primary prompt string for nonprivileged users , the system administrator uses the # prompt .We have something more to discuss about PS1 when we take up th Bash and Korn Shell .

Shell used by Commands with Shell Escapes ( SHELL ) -

SHELL tells you the shell you are using. There are some programs like more and vi that provide yu with a shell escape to let you run a UNIX command . SHELL determines the shell these programs use .

The system administrator usually sets up your loging shell in /etc/passwd when creating a user account , though he can cange it whenever you make a request . Just have a look at the sample line in the dicussion on the HOME variable , the last field sets the value of SHELL .

The Terminal Tyepe ( TERM ) -

TERM indicates the terminal type that is used . Every Terminlal has certain characteristics that are defined in a separate control file in the terminfo directory ( in /usr/lib or /usr/share/lib ) . This directory contains a number of subdirectories named after the letters of the alphabet . A terminal's control file is available in a directory having a one -letter name that is the same as the first letter of the terminal name . For instance , vt100 terminals use the file /usr/share/lib/terminfo/v/vt100.

Some utilities like the vi editor are terminal -dependent and they need to know the type of terminal you are using . If TERM isn't set correctly , vi won't work and the display will be faulty . TERM is also important when you log on to a remote machine .

Your Username ( LOGNAME) -

This variable shows your username . When you wander around in the file system , you may sometimes forget you login name . ( It's Strange , but it happens when you have multiple acccounts ! ) . From time to time , just make sure you know whcih account you logged in to :

echo $LOGNAME Or try whoami

mangesh

Where else can we use this variable ? You can use it in a shell script which does different things depending on the user invoking the script .

Field Separator for Command and Arguments ( IFS )

IFS contains a string of characters that are used as word separators in the command line . The string normally consist of the space , tab and newline charaters . All of these chracters are invisible but the balnk line following it suggests that the newline character is part of this string. You can confirm the contents of thsi variable by taking its octal dump .

echo "$IFS " | od -bc

0000000 040 011 012 012

0000004

We can see the three vwhitespace characters that comprises IFS. Shell programmers sometimes needs to make a temporary change to IFS .

Variable Function
HOME Home Directory - The directory a user is placed on logging in
PATH List of directories searched by the shell to locate a command
LOGNAME Login name of user
USER Login name of user
MAIL Absolute pathname of user's mailbox file
MAILCHECK Mail checking interval for incoming mail
TERM Type of terminal
PWD Absolute pathname of current directory ( Korn and Bash only )
CDPATH List of directories searched by cd when used with a nonabsolute pathname
PS1 Primary Prompt String
PS2 Secondary Prompt String
SHELL USer's Login Shell and one invoked by programms having shell escapes

Set Environment Variables on Linux -

You can modify each environmental or system variable using the export command. Set the PATH environment variable to include the directory where you installed the bin directory with perl and shell scripts:

For Korn shell (KSH)

The syntax is as follows:

var=value
export var

 

export PATH=${PATH}:/home/vivek/bin

OR

export PATH=${PATH}:${HOME}/bin

KSH shell use the following files:

  1. /etc/profile – This default system file is executed by the KSH and sets up default environment variables.
  2. $HOME/.profile – Put your customization in this file.

Aliases ( Bash and Ksh ) : 

Bash and Korn supports the use of aliases that let you assign shorthnad names to frequently used commands . We have covered this topic in detail under Linux Commands , Please see the page alias for more detials on aliases and its example

Command History ( Bash and Ksh ) : 

A serious drawback of the bourne shell is that a command has to be retyped to be reexecuted . Bash and korn support a versatile history feature that treats a previous command as an event and associates it with an event number .

The history command displays the history list showing the event number of every previously executed command . A command is recalled by using this event number with a symbol like ! or r . The maximum size and name of this file are determined by two shell-specific variable .

While Bash displays the complete history list with history , Korn lists the 16 commands most recently used , but we can easily find out last five commands by using a numeric argument .

history 5 ---------------- Bash

history - 5 --------------------- Korn

This output shows the event number and command associated with that number , and it coulld look like this :

 35 set -o ignoreeof
 36 exit
 37 alias l='ls -l'
 38 tar cvf /dev/fd0*.doc
 39 fc -l 
 40 history                Also includes command invoked to obtain list 

By default , Bash stores all previous commands in $HOME/.bash_history and SHOME/.sh_history in korn . When a command is entered and executed , it is appended to the list .

Knowing the event number may no be enough , you may need o repeat a previous command . Both bash and Korn allow you to doo that and these features are taken up in the following sections .

Accessing Previous Commands By Event Numbers ( ! and r ) : 

The ! symbol in Bash and r symbol in Korn shell is used to repeat previous commands . For repeating the last command , you have to use this :

   !!                 Repeat Previous Command in Bash 
   r                  Repeat Previous Command in Korn 

Just one or two characters , nothing could be simple that that ! You can repeat other commands using ! or r , but with the event number as argument :

   $ !38    ( Bash shell )   OR
   $ r38    ( Korn shell )
   $ 38 tar cvf /dev/fd0 *.c
Relative addresing : If you don't know the event number but want to execute the command prior to the previous one , we can use a negative rgument with ! or r :
   !-2     Bash--no space between ! and - 
   r -2    Korn Shell Command

 

Using Last Argument to Previous Commans ( $_ )

We often run several commands on the same file , and instead of specifying the filenameevery time we can now use $_ as the abreviated filename . This expression sifnifies the last arguments to the previous command .For instance , we create a directory with mkdir progs and then change to it with cd progs . We can use $_ as a shorthand feature to represent the directory used by the previous command .

    mkdir progs
    cd $_           Changes Directory to progs 

To consider another example , if you have edited a shell script cronfind.sh with vi , you can execute this file by simply entering this :

$_ --------------------------------------------------- Executes cronfind.sh

The History Variables

There are a few environment variables that influence the behaviour of the history mechanism in Bash and Korn Shell . First , the HISTFILE variable determines the filename that saves the history list . If it is not set , Bash and Korn use the following as the default history files in the home directory :

   .bash_history     Bash
   .sh_history       Korn   

The history list is maintained in memory also . Bash uses two separate variables , HISTSIZE and HISTFILESIZE , for setting the size of the history list in memory and on disk . Korn uses only HISTSIZE for both puposes . Here are two examples

   HISTSIZE=500            Bash and Korn 
   HISTFILESIZE=1000       Bash only --determines size of disk file   

with memory and disk space going cheap today , you should set these variables to large values sp you can store commands of multiple login sessions .

Miscellaneous Features ( bash and ksh ) -

Before moving on to the shell's intialization scripts lets considder a few features available in Bash and Korn which you will find quite useful . Two of them use the shell's set statement . We will also consider the significance of the ~ ( tilde ) in these shells .

Using Set -o

The set statementby default displays the variables in the current shel , but in Bash and Korn , it can make several environment settings with the -o option . This option , followed by a keyword , takes care of some of the common hazards faced by users , like overwritting files and accidental logging out .

File Overwritting ( noclobber)

The shell's > symbol overwrites ( clobbers) an existing file and to prevent such accidental overwriting , you have to use the noclobber argument in this way :

set -o noclobber --------------------------------------------------- No more overwritting files with >

This means that if you redirect output to an existing file sample.txt , the shell will report with a message :

bash : sample.txt : cannot overwrite existing file --------------------------------------------------- Bash

ksh : file already exists ---------------------------------------------------------------------------------- Korn

To override this protection feature , use the | after > :

head -n 5 emp.csv >| sample.txt

Accidental Logging Out ( ignoreoff ) -

Users often inadvertently press [ ctrl -d ] with intent to terminate standard input , but end up logging out of the system . The ignoreoff keyword offers protection from accidental logging out :

set -o ignoreoff --------------------------------------------------- [ ctrl - d ] won't log you out

Now , when you use [ ctrl -d ] to terminate your session , the shell typically respond like this :

Use 'exit' to terminate this shell

You can now have to use the exit command to take you out of the session ; [ctrl -d ] won't do any more ( unless executed repeatedly ! ) .

A set option in turned off with set +o keyword . To reverse the noclobber feature , use set +o noclobber . The complete list of set 's special options is obtained by using set -o or set +o without any additional arguments .

Tilde Substitution -

The ~ acts as a shorthand represntation of the home directory . When the ~ is followed by a ogin name , the shell understands the entire argument as the absolute pathname of the login directory . Thus , when the shell encounters the following command line

cd ~nikhil ---------------------------------------- Effectively becomes $HOME/nikhil

It switches to nikhil's home directory . If the value of $HOME is /home/nikhil/tulcel , this is the directory where cd ~nikhil switches to . Intrestingly , the ~ when used by itself or when immediately followed by a / , refers to the home directory of the user using it . If you have logged in as sharma, you can access the html directory under your home directory by using cd ~/html . That's why we often find a configuration file like .profile referred to both as $HOME/.profile and ~/.profile . The former works in the Bourne Shell also but not the latter .

You can toggle between the directory you switched to most recently and you current directory . This is done with the ~- symbols ( or simply - , a hyphn ) . For instance , either of the commands

   cd ~-       Chnages to your previous directory 
   cd -        Same               

Changes your current working directory to one you used most recently

The Initialization Scripts -

We have assigned values to many of the environment variables , defined aliases and used set options . These settings are applicable only for the session ; they revert to their default values when the user logs out . To make these setting permanent , you will have to place them in certain startup scripts .

Every shell uses at least one startup script in the user's home directory - muck like the AUTOEXEC.BAT file of DOS . This script is executed when the user logs in . Some shells also make use of a separate file that is run before logging out . Look in your home directory with ls -a and you will find one or more of these files

  • .profile ( Bourne Shell )
  • .profile and .kshrc ( Korn Shell )
  • .bash_profile ( or .profile or .bash_login ) and .basshrc ( Bash )

Bash has an elaborate startup system , but the system is not as complex as it may appear . We have two types of files here -- the "profiles" and "rc" files . The profils are executed only once , upon login . The rc files are designed to be executed every time a separate shell is created . Let's now examine these files and consider the entries that we can place in them .

The Profile ( .profile and .bash_pprofile ) -

The Bourne family uses .profile as the login script . As an added feature , the profile used by Bash can have one of three names - .bash_profile , .profile and .bash_login . Bash Looks for one of these files in the sequence specified and identifies the one it spots first as its profile .

Issue the ls -a command and see ehtehr you can locate one of these files in your home directory . This login script should be added to your home directory at the time of user creation , but you can create one even if it's not there . It is really a shell script that is executed by the shell when one logs on to the system . These "profiles" can be quite large depending on users requirements , but and abridged one should do for initial comprehension :

  $ cat.profile 
  # User $HOME/.profile - Commands executed at login time   
  MAIL=/var/mail/$LOGNAME       #mailbox location 
  PATH=$PATH:$HOME/bin:/usr/ucb:.
  PS1='$ '
  PS2=>
  TERM=vt100
  MOZILLA_HOME=/opt/netscape ; export MOZILLA_HOME
  stty stop ^S intr ^C erase ^?
  echo "Today's date is 'date` "  

The profile contains commands that are meant to be executeed only once in a session . Some of the system variables have been assigned in this script . The later statements shows that the file has been edited to taste . The PATH has been modified to contain three ore directories . Some tty setting have also been made here . All of these commands and variables are understood by the Bourne shell , s this script will work in all shells of the Bourne family .

The .profile let you customize your operating environment to suit your requirements . This environment remains in effect throughout the login session. Every time you make changes to this file , you should either log out and log in again or use a special command ( called dot ) to execute the file :

. .profile ------------------------------------ used by the Bourne Family
The .profile must be located in your home directory and it is executed after /etc/profile, the universal profile for all users . Universal environment settings are kept by the administrator in /etc/profile so they are available to all users .

The rc File ( bash and ksh ) -

There's no rc file in Bourne , but Bash and Korn use one . This file is defined by an environment variable ( BASH_ENV and ENV in Korn ) which should be specified in the profile ( .profile or .bash_profile ) . You should have one of these settings in your profile depending on the shell you use :

   exort BASH_ENV=$HOME/.bashrc      Bash; can also use BASH-ENV=~/.bashrc
   export ENV=$HOME/.kshrc           Korn; can also use ENV=~/.kshrc

This file is executed every time a second shell is called up ( when running a shell script , for instance ) . However , there's a little difference in the way Bash and Korn use their rc file . Korn automatically executes .kshrc during login if ENV is defined in the way shown above . However the above Bash definition merely ensures that a sub-shell executes this file . If the login shell also has to execute this file , then a separate statement must be added in the profile :

 . ~/.bashrc                   Bash ; can also use source ~/.bashrc

The environment file should be used to hold only Bash or Korn specific features . History list settings ( like HISTSIZE and HISTFILE ) , command editing settings ( like set -o vi ) and alias definitions should all be made in the environment file . This is a character arrangement because should you decide to change your shell any time later , you won't be saddled with a .profile ridden with irrelevant entries . Here are some sample entries :

   alias cp="cp -i"
   alias rm="rm -i"
   set -o noclobber 
   set -o vi
   set -o ignoreoff

This rc file will be executed after the profile . However , if the BASH-ENV or ENV variable isn't set , the shell executes only the profile .

Untitled Document Scroll To Top Untitled Document