Variables in linux 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”.
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” ]
echo “$xyz is NULL.”

We can also assign values to the variables using below syntax.
lsoutput=`ls -l`
echo $lsoutput


let “a = a+ 1”

echo $a

To display current bash version, you can use below enviornment

Here is the list of some of the important enviornment variables.
  • $CDPATH – list of search paths available to the cd command.
  • $DIRSTACK – top most value in stack used with pushd and popd.
  • $OLDPWD – old working directory
  • $BASHPID – Current Bash PID
  • $OSTYPE – Operating system type
  • $PATH – PATH variable contains the list of paths seperated by :
  • $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.
  • display all variables.
  • It is also used to set the positional parameters.
  • 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.
declare -r variable1
readonly variable1

Web development and Automation testing

solutions delivered!!