Topic 2
3/5/2021
1
Topic 2
SHELL VARIABLES AND THE BASH ENVIRONMENT
Variables
Global Variables (aka environment/system variables) – are available in all shells. Can use env or
printenv commands to display. The set command will also work, but it will also display
environment functions. Most are defined in CAPITAL LETTERS. You can configure aspects of the
shell by modifying the system variables such as PS1, PATH, LANG, …
Local Variables – only available in the current shell. Can use set command to display a list of all
variables (including environment variables) and functions.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 2
3/5/2021
2
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 3
System Variable Meaning
To View Variable Value
Type
BASH_VERSION Holds the version of this instance of bash. echo $BASH_VERSION
HOSTNAME The name of the your computer. echo $HOSTNAME
CDPATH The search path for the cd command. echo $CDPATH
HISTFILE
The name of the file in which command history is
saved.
echo $HISTFILE
HISTFILESIZE
The maximum number of lines contained in the
history file.
echo $HISTFILESIZE
HISTSIZE
The number of commands to remember in the
command history. The default value is 500.
echo $HISTSIZE
HOME The home directory of the current user. echo $HOME
IFS
The Internal Field Separator that is used for word
splitting after expansion and to split lines into
words with the read builtin command. The
default value is
echo $IFS
Commonly Used Shell Variables
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 4
System Variable Meaning
To View Variable Value
Type
LANG
Used to determine the locale category for any category
not specifically selected with a variable
starting with LC_.
echo $LANG
PATH
The search path for commands. It is a colon-separated list
of directories in which the shell looks for commands.
echo $PATH
PS1 Your prompt settings. echo $PS1
TMOUT
The default timeout for the read built-in command. Also in
an interactive shell, the value is interpreted as the number
of seconds to wait for input after issuing the command. If
not input provided it will logout user.
echo $TMOUT
TERM Your login terminal type.
echo $TERM
export TERM=vt100
SHELL Set path to login shell. echo $SHELL
DISPLAY Set X display name
echo $DISPLAY
export DISPLAY=:0.1
EDITOR Set name of default text editor.
export
EDITOR=/usr/bin/vim
3/5/2021
3
Displaying Variables – echo command
All variable names must be prefixed by the $ symbol and the entire construct should be enclosed
in quotes.
echo “$PATH”
echo “$HOME”
echo “$PS1”
Enclosing the variable name in braces is useful for combining it with something else
echo “${HOME}work”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 5
Displaying Variables – printf command
Printf works like the echo command and usually preferred over echo, especially if portability is a
concern. The syntax is as follows:
printf “$VARIABLE_NAME\n”
printf “String %s” $VARIABLE_NAME
printf “Signed Decimal Number %d” $VARIABLE_NAME
printf “Floating Point Number %f” $VARIABLE_NAME
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 6
3/5/2021
4
Creating variables
◦ Variables are case sensitive and capitalized by default
◦ Local variables often have lowercase names
◦ Variables can contain digits, but can’t begin with a digit – i.e. 1num is not a valid variable name
◦ Good practice to avoid all caps to differentiate from environment variables.
Syntax to set a variable name:
VARNAME=“value”
Note: There are no spaces around the equal sign. Doing so will cause an error.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 7
echo vs printf
Use echo command to display a line of text or a variable value. It offers no formatting option. It
is a good command to display a simple output when you know that the variable’s contents will
not cause problems. For most uses, printf is preferable.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 8
3/5/2021
5
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 9
#!/bin/bash
# Display welcome message, computer name and date
echo “*** Backup Shell Script ***”
echo
echo “*** Run time: $(date) @ $(hostname)”
echo
# Define variables
BACKUP=”/nas05″
NOW=$(date +”%d-%m-%Y”)
# Let us start backup
echo “*** Dumping MySQL Database to $BACKUP/$NOW…”
# Just sleep for 3 secs
sleep 3
# And we are done…
echo
echo “*** Backup wrote to $BACKUP/$NOW/latest.tar.gz”
Output with printf command
Format control string syntax is as follows:
printf “%w.pL\n” $varName
Where,
◦ w – Minimum field width
◦ p – Display number of digits after the decimal point (precision).
◦ L – a conversion character. It can be:
◦ s – String
◦ d – Integer
◦ e – Exponential
◦ f – Floating point
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 10
3/5/2021
6
printf Command Examples
vech=”Car”
printf “%s\n” $vech
printf “%1s\n” $vech
printf “%1.1s\n” $vech
printf “%1.2s\n” $vech
printf “%1.3s\n” $vech
printf “%10.3s\n” $vech
printf “%10.1s\n” $vech
no=10
printf “%d\n” $no
big=5355765
printf “%e\n” $big
printf “%5.2e\n” $big
sales=54245.22
printf “%f\n” $sales
printf “%.2f\n” $sales
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 11
Assigning values
assignDIR=“$HOME/Documents/CS018/Assignments”
Common Examples
Define your home directory:
myhome=“/home/jleon/”
Set file path:
input=“/home/sales/data.txt”
set
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 12
3/5/2021
7
Special Bash Variables
Character Definition
$* Expands the positional parameters, starting from one. When the expansion occurs within
double quotes, it expands to a single word with the value of each parameter separated by
the first character of the IFS special variable.
$@ Expands to the positional parameters, starting from one. When the expansion occurs within
double quotes, each parameter expands to a separate word.
$# Expands to the number of positional parameters in decimal
$? Expands to the exit status of the most recently executed foreground pipeline.
$- A hyphen expands to the current option flags as specified upon invocation, by the set built-
in command, or those set by the shell itself (such as the -i).
$$ Expands to the process ID of the shell.
$! Expands to the process ID of the most recently executed background (asynchronous)
command.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 13
Character Definition
$0 Expands to the name of the shell or shell script.
$_ The underscore variable is set at shell startup and contains the absolute file name of the shell
or script being executed as passed in the argument list. Subsequently, it expands to the last
argument to the previous command, after expansion. It is also set to the full pathname of
each command executed and placed in the environment exported to that command. When
checking mail, this parameter holds the name of the mail file.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 14
3/5/2021
8
Quoting Characters
A lot of keys/characters have special meanings in certain contexts. Quoting allows us to remove
the special meaning of characters or words. Quotes can
◦ Disable special treatment for characters
◦ Prevent reserved words from being recognized
◦ Disable parameter expansion
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 15
There are three types of quotes:
Quote
Type
Name Meaning Example (type at shell prompt)
“ double
quote
Protects everything enclosed between two
double quote marks except $, ‘, “ and \. Use
the double quotes when you want only
variables and command substitution.
• Variable – Yes
• Wildcards – No
• Command substitutions – Yes
Allows you to print the value of the $SHELL
variable, disables meaning of wildcards, and
finally allows command substitution.
echo “$SHELL”
echo “/etc/*.conf”
echo “Today is $(date)”
‘ single
quote
Protects everything enclosed between two
single quote marks. It is used to turn off the
special meaning of all characters.
• Variable – No
• Wildcards – No
• Command substitutions – No
The single quotes prevents displaying
variable $SHELL value, disabled the
meaning of wildcards /etc/*.conf, and
finally command substitution ($date) itself.
echo ‘$SHELL’
echo ‘/etc/*.conf’
echo ‘Today is $(date)’
\ backslash Use backslash to change the special meaning
of characters or to escape special characters
within the text such as quotation marks.
Use \ before $ to disable special meaning.
echo “Today is $(date)”
echo “Today is \$(date)”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 16
3/5/2021
9
The Backslash
The backslash (\) alters the special meaning of the ‘ and “ i.e. it will cancel the special meaning
of the next character.
FILE=“/etc/resolv.conf”
echo “File is \”$FILE\” “
Sample Output:
File is “/etc/resolv.conf”
Recall in the previous slide that we were able to remove the special meaning of the $
echo “Today is $(date)”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 17
Backslash-escaped characters
You can use the following backslash-escaped characters (using ANSI C standard). From bash man page:
\a alert (bell)
\b backspace
\e an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\’ single quote
\nnn the eight-bit character whose value is the octal value nnn (one to three
digits)
\xHH the eight-bit character whose value is the hexadecimal value HH (one or
two hex digits)
\cx a control-x character
Use –e option of echo command to enable interpretation of backslash escapes.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 18
3/5/2021
10
Backslash – Examples
echo “Pizza bill \$22.5”
echo -e “\a Ding dong\a”
echo “CIFS path must be \\\\NT-Server-Name\\ShareName”
echo -e “Sr.no\t DVD (price) ”
echo -e “1\t Spirited Away (INR.200)”
echo -e “2\t Dragon Ball Z (INR.300)”
Disable the special meaning of * and @ inside double quotes.
echo “*”
echo “\*”
echo “\@”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 19
Backslash – continue on next line
You can use the backslash to continue a command on the next line
printf “%s\n” “This is a very long printf. How long is it?\
> It’s so long that I continued it on the next line.“
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 20
3/5/2021
11
The Export Statement
The export built-in automatically exports to the environment of child processes. Example,
vech=“Bus“
echo “$vech”
Now, start a new shell instance and display value of vech:
bash
echo “$vech”
You will get an empty line. So use the export command to export the vech variable to the child
process.
export vech
Use the unset command to delete variables during program execution.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 21
Getting User Input Via Keyboard
You can accept input from the keyboard and assign an input value to a user defined shell
variable using the read command.
read Command Syntax:
read -p “Prompt” variable1 variable2 variableN
Where,
◦ P “Prompt”: Display prompt to user without a newline.
◦ variable1: The first input(word) is assigned to variable1.
◦ variable2: The second input(word) is assigned to variable2.
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 22
3/5/2021
12
Performing arithmetic operations
Arithmetic expansion and evaluation is done by placing an integer expression using the following
format:
$((expression))
$(( n1+n2 ))
$(( n1/n2 ))
$(( n1-n2 ))
Examples
Add two numbers on fly using the echo command:
echo $(( 10 + 5 ))
Add two numbers using x and y variable. Create a shell program called add.sh using a text editor:
#!/bin/bash
x=5
y=10
ans=$(( x + y ))
echo “$x + $y = $ans”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 23
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 24
Operator Description Example Evaluates To
+ Addition echo $(( 20 + 5 )) 25
– Subtraction echo $(( 20 – 5 )) 15
/ Division echo $(( 20 / 5 )) 4
* Multiplication echo $(( 20 * 5 )) 100
% Modulus echo $(( 20 % 3 )) 2
++ post-increment (add variable value by 1)
x=5
echo $(( x++ ))
echo $(( x++ ))
5 6
—
post-decrement (subtract variable value by
1)
x=5
echo $(( x– ))
4
** Exponentiation
x=2
y=3
echo $(( x ** y ))
8
3/5/2021
13
Create an integer variable
• To create an integer variable use the declare command as follows:
declare -i y=10
echo $y
• Create a shell script called intmath.sh:
#!/bin/bash
# set x,y and z to an integer data type
declare -i x=10
declare -i y=10
declare -i z=0
z=$(( x + y ))
echo “$x + $y = $z”
# try setting to character ‘a’
x=a
z=$(( x + y ))
echo “$x + $y = $z”
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 25
Create the constants variable
You can create the constants variables using the readonly command or declare command. The readonly
buitin syntax is as follows:
readonly var
readonly varName=value
The declare builtin syntax is as follows:
declare -r var
declare -r varName=value
Example
Create a constant variable called DATA and make its value always the same throughout the shell script i.e. it
can’t be changed:
readonly DATA=/home/sales/data/feb09.dat
echo $DATA
/home/sales/data/feb09.dat
DATA=/tmp/foo
TOPIC 2 – SHELL VARIABLES AND THE BASH ENVIRONMENT 26