Variables in shell scripting

To create a variable, use below syntax. Please do not give spaces before or after = sign. In below example, we have created a variable with name “mypath” and assigned it a value “/etc”.

mypath=/etc
cd “$mypath”

#below statement is same as above. It is recommended to use {} around the variable name to avoid getting errors.
cd “${mypath}”

#below command will print $mypath as it is. There will be no variable substitution.It preserves all characters in ‘ ‘ as it is.

cd ‘$mypath’

You can use below code to check if certain variable is a NULL or Not NULL. Here -z means return true if the variable is NULL.

if [ -z “$xyz” ]
then
echo “\$xyz is NULL.”
fi

We can also assign values to the variables using below syntax.

lsoutput=`ls -l`
echo $lsoutput

lsoutput=$(ls)

a=100
let “a = a+ 1”

echo $a

To display current bash version, you can use below enviornment
echo $BASH_VERSION

Here is the list of some of the important enviornment variables.

  1. $CDPATH – list of search paths available to the cd command.
  2. $DIRSTACK – top most value in stack used with pushd and popd.
  3. $OLDPWD – old working directory
  4. $BASHPID – Current Bash PID
  5. $OSTYPE – Operating system type
  6. $PATH – PATH variable contains the list of paths seperated by :
  7. $SHLVL – Shell level

Note that environment variables are accessible to any script in the system.

declare command in Linux

You can use declare command to declare the variables with special attributes.

We can declare read only variable using below syntax.
declare -r pi=3.14

We can declare integer variable using below syntax.
declare -i age=22

We can declare array using below syntax.
declare -a myarray

We can define the function using below syntax.
declare -f functionName

declare is also used for printing all variables.

set command in Linux

set command is used to do below things.

  1. display all variables.
  2. It is also used to set the positional parameters.
  3. It is also used to modify the internal shell variables.

unset command in Linux

unset command is used to delete the variable.

export command in Linux

export command is used to make the variable available to all child shell and processes.

typeset command in Linux

typeset command is used to change the variable attributes.

Read only variables

We can create read only variables in 2 ways.

  1. declare -r variable1
  2. readonly variable1

You may also like...