Shell Unix Variable Assignment

Creating and setting variables within a script is fairly simple. Use the following syntax:

someValue 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}:








For example, create a variable called vech, and give it a value 'Bus', type the following at a shell prompt:

Display the value of a variable vech with echo command:


Create a variable called _jail and give it a value "/", type the following at a shell prompt:

_jail="/"printf"The java jail is located at %s\nStarting chroot()...\n"$_jail


n=10# this is ok10=no# Error, NOT Ok, Value must be on right side of= sign.

Common Examples

Define your home directory:


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):

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<="


Sample outputs:


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:


Sample outputs:


You're looking for the shell feature called command-substitution.

There are 2 forms of cmd substitution

  1. Original, back to the stone-age, but completely portable and available in all Unix-like shells (well almost all).

    You enclose your value generating commands inside of the back-ticks characters, i.e.

  2. Modern, less clunky looking, easily nestable cmd-substitution supplied with , i.e.

Your 'she-bang' line says, , so if you're running on a real Unix platform, then it's likely your is the original Bourne shell, and will require that you use option 1 above.

If you try option 2 while still using and it works, then you have modern shell. Try typing or and see if you get any useful information. If you get a version number, then you'll want to learn about the extra features that newer shells contain.

Speaking of newer features, if you are really using bash, zsh, ksh93+, then you can rewrite your sample code as

Or if you're doing more math operations, that would all stay inside the scope, you can use shell feature arithmetic like:

In either case, you can avoid extra process creation, but you can't do floating point arithmetic in the shell (whereas you can with ).


Leave a Reply

Your email address will not be published. Required fields are marked *