3. The Environment
We have seen previously some environment variables. These are variables that are maintained by the shell and are used to store some settings. They can also be used by some programs to get configuration values.
-
We can display a list of environment variables with
printenvorset:printenv | lessset | lessThe list displayed by
setis longer because it displays also shell variables and some functions defined in the shell.printenv USERecho $USERThe
USERvariable basically keeps the value that is displayed by the commandwhoami. -
Some other interesting environment vars are these:
echo $HOMEecho $PWDecho $SHELLecho $LANGecho $PATHPATHis used by shell to find a program. For example when we callls, shell is looking for it in the first directory of the PATH, then in the second, and so on. The commandwhich lsshows us where the shell finds the programls. -
The environment variables are declared in some configuration files that the shell loads when it starts. There are two kinds of shells: a login shell session, which is started when we are prompted for a username and password, and a non-login shell session, which is started when we launch a terminal.
The configuration scripts loaded by a login shell:
nano /etc/profilenano ~/.profileNote: Type Ctrl-x to exit from
nano.The configuration scripts loaded by a non-login shell:
nano /etc/bash.bashrcnano ~/.bashrcHowever the non-login shell inherits the environment variables from the parent process, usually a login shell, and the config scripts of a login shell usually include the config scripts of a non-login shell. So, if we want to make some changes to the environment, the right place to edit is the file
~/.bashrc. -
Let's say that we want to modify the variable HISTSIZE, which keeps the size of the command history.
echo $HISTSIZEnano ~/.bashrcAdd this line at the end of the file:
export HISTSIZE=2000Press Ctrl-o and Enter to save the changes. Then Ctrl-x to exit.
With
HISTSIZE=2000we are giving a new value to the variable, and the commandexportactually saves it to the environment of the shell.Next time that we will start a shell it will load
~/.bashrcand a new value will be set to HISTSIZE. But we can also load~/.bashrcwith the commandsource, so that the changes are applied right now:echo $HISTSIZEsource ~/.bashrcecho $HISTSIZE -
One of the environment variables is
PS1, which defines the prompt:echo $PS1Let's try to play with it, but first let's backup the current value:
ps1_old="$PS1"echo $ps1_oldIf we need to restore we can do it like this:
PS1="$ps1_old"Let's try some other prompts:
PS1="--> "ls -alPS1="\$ "ls -alPS1="\A \h \$ "ls -al"\A" displays the time of day and "\h" displays the host.
PS1="<\u@\h \W>\$ "ls -al"\u" displays the user and "\W" displays the name of the current directory.
To save this prompt for future sessions of the shell, we should append this line to
~/.bashrc:export PS1="<\u@\h \W>\$ "