Working with Unix Variables: Features of Shell Scripting

Features of Shell Scripting: Unix Variables

Shell variables provide us the ability to store and manipulate information within a shell program.

In this tutorial, we return to shell scripts and understand how to work with variables. Variables are used to change the flow of the program and to maintain the state. 

Unix Video #13:

Defining a Variable

A variable is defined by simply assigning a value to a name using the ‘=’ operator. A variable name is a series of alphanumeric characters starting with a letter or ‘_’.  Variables are all treated as text strings unless the context requires them to be treated as a numeric value.

Example:

$ myvar=hello
$ mycount=1

In case the value needs to include spaces, it can be surrounded by double quotes.

Example:

$ myvar1=”hello there!”

Accessing a Variable

A variable name is de-referenced by simply adding a ‘$’ prefix to it.  The ‘echo’ command is often used to print the value of a variable.

Example:

$ echo $myvar
hello

A variable will be treated as a numeric value if it is used with the ‘expr’ command.

Example:

$ expr $mycount + 2
3

The variable name needs to be surrounded by braces if in case it is not followed by a space.

Example:

$ echo ${myvar}oo
hellooo

When using double quotes, special characters like ‘$’ retain their special meaning.

Example:


$ myvar2=”$myvar there!”
$ echo $myvar2
hello there!

If in case the special characters need to be treated literally, single quotes may be used.

Example:

$ myvar3=’$myvar there!’
$ echo $myvar3
$myvar there!

Types of Variables

#1) Environment variables:

These are the variables that are visible to the child processes of a shell program.   These include special environment variables that are set by the shell and are required for the shell to function properly.

Example:

  • $PATH – The set of paths to search for commands.
  • $HOME – The path to the current user’s home folder.

#2) Predefined variables:

When running commands, the shell expands wildcards, and then assigns the arguments to these predefined variables or ‘positional variables’.

Example:

  • $0 – The name of the command being executed.
  • $1 … $9 – The first to ninth arguments.

#3) User-defined variables:

These are the variables that are visible to the current instance of the shell.  The ‘export’ command is used to expose local variables to the environment variables.

Other Shells:

When using csh, variables are defined using the ‘set’ command and they are exported as environment variables using the ‘setenv’ command.

Along with the scalar variables described above, the bash shell supports array variables also.

Our upcoming tutorial will explain more about Working with Arithmetic Operators in Unix!!

PREV Tutorial | NEXT Tutorial