Unix Tutorial 10 : Variables

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.

Comments

Popular posts from this blog

Hive Tutorial 31 : Analytic Functions

Hive Tutorial 37 : Performance Tuning

How to change sqoop saved job parameters