Assign values to shell variables
Creating and setting variables within a script is fairly simple. Use the following syntax:
varName=someValuesomeValue is assigned to given varName and someValue must be on right side of = (equal) sign. If someValue is not given, the variable is assigned the null string.
How Do I Display The Variable Value?
You can display the value of a variable with echo $varName or echo ${varName}:
echo "$varName"
OR
echo "${varName}"
OR
printf "${varName}"
OR
printf "%s\n" ${varName}
For example, create a variable called vech, and give it a value 'Bus', type the following at a shell prompt:
vech=BusDisplay the value of a variable vech with echo command:
echo "$vech"
OR
echo "${vech}"
Create a variable called _jail and give it a value "/httpd.java.jail_2", type the following at a shell prompt:
_jail="/httpd.java.jail_2" printf "The java jail is located at %s\nStarting chroot()...\n" $_jail
However,
n=10 # this is ok 10=no# Error, NOT Ok, Value must be on right side of = sign.
Common Examples
Define your home directory:
myhome="/home/v/vivek" echo "$myhome"
Set file path:
input="/home/sales/data.txt" echo "Input file $input"
Store current date (you can store the output of date by running the shell command):
NOW=$(date) echo $NOW
Set NAS device backup path:
BACKUP="/nas05" echo "Backing up files to $BACKUP/$USERNAME"
More About ${varName} Syntax
You need to use ${varName} to avoid any kind of ambiguity. For example, try to print "MySHELL=>$SHELLCode<="
echo "MySHELL=>$SHELLCode<="
Sample outputs:
MySHELL=><=
The bash shell would try to look for an variable called SHELLCode instead of $SHELL. To avoid this kind of ambiguity use ${varName} syntax i.e. ${BASH}Code:
echo "MySHELL=>${SHELL}Code<="
Sample outputs:
MySHELL=>/bin/bashCode<=