Basic Linux Shell Scripting Concepts


Shell scripts become more useful through the use of variables. Variables store information to be used at a later time. To define a variable, simply assign it a value as follows.

[myVar=”Hello World”]

Then to retrieve the value, prefix the variable with a $. Note that all variables are case sensitive.

[Echo $myVar]

Variables can be numeric as well. This are treated no differently than string variables.



Result = $Num1+$Num2

Echo The answer is $Result

Note that variables do not have to be defined in the shell script to be used. Environment variables can also be referenced as well. This allows you to create scripts that reference home directories, application directories and environment settings.

Conditional Logic

Conditional execution of programs is accomplished via IF statements. In the bash shell, the syntax is as follows.

if test; then
elif test; then

The test is a logical operation that evaluates to true or false. If the evaluation is true then the code in the statement executes. Here are some examples of expressions.

Expression, Purpose

[ -f “somefile” ]: Test if somefile is a file.

[ -x “/bin/ls” ]: Test if /bin/ls exists and is executable.

[ -n “$var” ]: Test if the variable $var contains something

[ “$a” = “$b” ]: Test if the variables “$a” and “$b” are equal

Here is an example of a script that uses the environment variable to check what the users shell is.

if [ "$SHELL" = "/bin/bash" ]; then
echo "You are using BASH)"
echo "You are not using BASH, you are using $SHELL"