Shell Environment

In this section, we will be deep dive into linux user defined variables, system variables, shell commands, and more

Variables

Introduction to Variables

Variables are how programming and scripting languages represent data. A variable is nothing more than a label, a name assigned to a location or set of locations in computer memory holding an item of data. Variables appear in arithmetic operations and manipulation of quantities, and in string parsing.

Variables are off two types,

  • User defined variables
  • Environmental variables.

User Defined Variables

The name of a variable is a placeholder for its value, the data it holds. Referencing (retrieving) its value is called variable substitution. Convention should be followed for these variables, and it should be in small letters.

Let us carefully distinguish between the name of a variable and its value. If variable1 is the name of a variable, then $variable1 is a reference to its value, the data item it contains.

variable1=23

echo variable1
# output
variable1

echo $variable1
# output
23

Note:

Unlike many other programming languages, shell does not segregate its variables by “type.” Essentially, shell variables are character strings, but, depending on context, it permits arithmetic operations and comparisons on variables.

Variable Assignment

Assignment Operator: =

The assignment operator (no space before and after) Do not confuse this with = and -eq, which test, rather than assign!

Note:

= can be either an assignment or a test operator, depending on context

Special Variable Types

Local Variables

Variables visible only within a code block

Environmental Variables

Variables that affect the behavior of the shell and user interface.

In a more general context, each process has an environment, that is, a group of variables that hold information that the process may reference. In this sense, the shell behaves like any other process. Every time a shell starts, it creates shell variables that correspond to its own environmental variables. Updating or adding new environmental variables causes the shell to update its environment, and all the shell’s child processes (the commands it executes) inherit this environment.

Variable Naming Conventions

  • Variable name must begin with Alphanumeric character or underscore character (_), followed by one or more Alphanumeric character.

Example: Valid shell variables

HOME
SYSTEM_VERSION
vech
  • Don’t put spaces on either side of the equal sign when assigning value to variable.

Example: In following variable declaration there will be no error

no=10

Example: But here there will be problem for following

no =10
no= 10
no = 10
  • Variables are case-sensitive, just like filename in Linux.

Example:

no=10
No=11
NO=20
nO=2

Above all are different variable name, so to print value 20 we have to use $ echo $NO and Not any of the following

echo $no # will print 10 but not 20
echo $No # will print 11 but not 20
echo $nO # will print 2 but not 20
  • You can define NULL variable as follows (NULL variable is variable which has no value at the time of definition)

Example:

vech=
vech=""

Try to print its value $echo $vech, Here nothing will be shown because variable has no value i.e. NULL variable.

  • Do not use ?, *, etc., to name your variable names.

expr (expressions)

To do sum or math operations in shell use expr.

Syntax:

expr op1 operator op2

Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be,

  • Addition
  • Subtraction / Division % Modular, to find remainder For e.g. 20 / 3 = 6, to find remainder 20 % 3 = 2, (Remember its integer calculation) * Multiplication

Example:

expr 6 + 3
# output
9
# another example
x=20
y=5
expr x / y
# output
4

Note:

echo 6 + 3 will print 6 + 3, not the sum 9. Try yourself.

Few System Variables

You can see the system variables using the like, set, env. Some system variables are,

System VariableDescription
BASH=/bin/bashshell name
BASH_VERSION=1.24.7(1)shell variable name
COLUMNS=80Number of display columns on screen
HOME=/home/myhomeHome directory
PATH=/usr/bin:/usr/sbin:/bin:/sbin/Path setting. When a shell script is fired, it will search in PATH location
Interfaces are not supported in C++Java supports interfaces

Caution:

Modifying system variable can sometimes create problems.

Shell Commands And Execution

Every command is internally a script. So, the basic commands will work anywhere within the shell environment, because it is set in the PATH variable. Similarly, a user can also include the external command(i.e. script) in the PATH variable, so that he can execute the script anywhere in the shell environment.

The following steps show adding the new path to existing PATH variable.

For example, we want to run file1.sh from any location in cli.

file1.sh
file1.sh: command not found

For example, the $PATH variable has the following assigned,

echo $PATH
/home/john/:/usr/local/bin:/usr/bin:/bin

Add current directory to the $PATH variable. Assume in /users/john/proj1 directory, there is a script by name file1.sh

pwd
# output
/users/john/proj1
# set the path
$PATH=$PATH:/users/john/proj1
# run the script from anywhere from cli
./file1.sh
# output
Hello, World!

Advanced Shell Script Commands

/dev/null

/dev/null - Use to send unwanted output of program

Syntax:

{command} > /dev/null

Example: output of following command is not shown on screen its send to this special file.

ls > /dev/null

The /dev directory contains other device files. The files in this directory mostly represent peripheral devices such disks liks floppy disk, sound card, line printers etc.

Export Command

Normally all our variables are local. Local variable can be used in same shell, if you load another copy of shell (by typing the /bin/bash at the $ prompt) then new shell ignored all old shell’s variable.

Example:


vech=Bus   # local variable created

echo $vech # echo local variable
# output
Bus

/bin/bash  # load second shell in-memory - which ignores all old variables.

echo $vech # outputs nothing

vech=Car   # create new local variable with same name

echo $vech # echo local variable

exit       # exit the newly created shell

echo $vech # output variable value from previously created shell

We can use old shell’s variable to new shell (i.e. first shells variable to seconds shell), such variable is know as Global Shell variable. To do this use export command

Syntax:

export variable1, variable2,.....variableN

Example:

vech=Bus   # local variable created
echo $vech # output local variable
# output
Bus

export vech # create global variable

/bin/bash   # create new shell

echo $vech  # prints "Bus", because it is a global variabl
# output
Bus

exit        # Exit the newly created shell

echo $vech  # Echo variable
# output
Bus

Aliases

An alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding typing a long command sequence.

If, for example, we include alias lm="ls -l | more" in the startup file, then each lm typed at the command line will automatically be replaced by a ls -l | more. This can save a great deal of typing at the command line and avoid having to remember complex combinations of commands and options.

Setting alias rm="rm -i" (interactive mode delete) may save a good deal of grief, since it can prevent inadvertently losing important files.

In a script, aliases have very limited usefulness. Moreover, a script fails to expand an alias itself within compound constructs, such as if/then statements, loops, and functions.

An added limitation is that an alias will not expand recursively. Almost invariably, whatever we would like an alias to do could be accomplished much more effectively with a function.

Example: May use either single (’) or double (") quotes to define an alias.

alias ll="ls -l"

unalias is a command which is used to remove the alias that was set previously.

Example: It will remove the alias and ll will no more give long listing of files.

unalias ll

To display the command which has been set for an alias, type the following

alias lm

Quoting

Since the shell is full of special characters (with special meanings), we need a way to suppress the meaning of a special character. If we have a string which contains a special character we may not want it treated as such. If you were to assign a string of characters to a parameter, and the characters contained blanks and characters with a dual meaning (blanks in this case would indicate the end of the parameter assignment), you may receive an error message. When you quote a character or string of characters with single quotes (’), you suppress any special meaning. Other quote marks have different effects.

types of Quoting

  • Double quotes
  • Single quotes
  • Back quotes
  • Back slash

Back slash

The backslash () will cancel, or escape, the special meaning of the next character:

echo \$dir1

The above command will echo $dir1" instead of the parameter value of \dir1" because the dollar sign is told to have no special meaning. In this example, the $ has been escaped. Note that there’s no harm done in escaping non-special characters.

The Double Quote

The double quote " quotes anything enclosed in two double quotes except \ $ " ' and ` (grave accent). For example: echo "$dir1 is an \"old directory\"" The dollar sign interprets dir1 as a parameter; the backslash \ ignores the following double quote (in other words, it does not end the echo string but includes the double quote as part of it).

The Single Quote

The single quote ' will quote everything enclosed in two single quotes except the single quote itself. So the above example could be represented as

echo $dir1' is an "old directory"'

Notice where the single quotes begin. If we place $dir1 inside the single quotes, the value of dir1 will not be printed, rather the exact characters $dir1 since the dollar sign would be ignored as a special character.

Note

If you leave of a quote when entering commands in the shell, you will receive a secondary prompt (usually a >"). This just means you need to type in the closing quote.

The Single Quote

The single quote ' will quote everything enclosed in two single quotes except the single quote itself. So the above example could be represented as

echo $dir1' is an "old directory"'

Notice where the single quotes begin. If we place $dir1 inside the single quotes, the value of dir1 will not be printed, rather the exact characters $dir1 since the dollar sign would be ignored as a special character. Note If you leave of a quote when entering commands in the shell, you will receive a secondary prompt (usually a >"). This just means you need to type in the closing quote.

Command Substitution

The grave accent ` indicates a command substitution. Note Pay particular attention to the difference between the grave accent ` and the single quote '. The single quote is usually located below the double quote " and the grave accent is under the tilde (~). Command substitution means you can substitute a shell command’s output into a string like the echo string.The command is a shell command and must be enclosed between grave accents.

The following example shows a command substitution in an echo command, with the output from the command substitution appearing on the same line as the echoed words

echo "The current date and time is `date`."
# output
The current date and time is Wed May 30 15:24:35 MDT 2022.

The following example shows a command substitution in an echo command with the output from the command substitution appearing on lines following

the line with the echoed words

echo "People currently on the system:\n\n `who`"
# output
People currently on the system:

billa console May 30 09:45
stu tty02 May 30 12:02

Escaping

Escaping is a method of quoting single characters. The escape \ preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo, awk and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.

Special meanings of certain escaped characters used with echo, awk and sed

Escaped CharecterDescription
\nnew line
\rreturn
\ttab
\vvertical tab
\bbackspace
\a“alert” (beep or flash)

Subscribe For More Content