"Taking a LiveFire Labs' course is an excellent way to learn
Linux/Unix. The lessons are well thought out, the material is
explained thoroughly, and you get to perform exercises on a real
Linux/Unix box. It was money well spent."
Ray S.
Pembrook Pines, Florida
LiveFire Labs' UNIX and Linux Operating System Fundamentals
course was very enjoyable. Although I regularly used UNIX systems
for 16 years, I haven't done so since 2000. This course was a
great refresher. The exercises were fun and helped me gain a real
feel for working with UNIX/Linux OS. Thanks very much!"
Ming Sabourin
Senior Technical Writer
Nuance Communications, Inc.
Montréal, Canada
Read
more student testimonials...
Receive UNIX Tips, Tricks, and Shell Scripts by Email
LiveFire Labs' UNIX Tip,
Trick, or Shell Script of the Week
Useful Shell Script Variables - Part I - PWD
There are a number of shell script variables, both built-in and
user-defined, that are helpful and at times essential for building
both basic and complex shell scripts. This series of tips will
present some of the more commonly used members from this group,
explain what they contain, and provide examples of how they may be
used when writing scripts.
The built-in variable PWD stores the present working directory, which
is also referred to as the current working directory. Each time the
cd (change directory) command is issued, ksh updates the value stored
in this variable to reflect the new directory location. In the
following example, the starting directory was /tmp, and then was
changed to /usr/bin:
$ print $PWD
/tmp
$ cd /usr/bin
$ print $PWD
/usr/bin
$
One use for PWD in scripts is to validate the directory the user is
in, when he or she invokes your shell script, against an acceptable
list of directories. The directory may need to be an exact match to a
directory from the list, or can also be a subdirectory of one of the
directories. If the latter, some additional logic would need to be
included in the script to perform an adequate comparison of the two
values.
This short shell script demonstrates how PWD can be used to check for
an exact directory match:
#!/bin/ksh
#
# Filename: dir_chk
# Description: checks if user's PWD is /tmp
#
if [ $PWD = /tmp ]
then
print "PWD is /tmp"
else
print "PWD is NOT /tmp"
fi
exit
The if-then-else statement in this script may be compressed into a
single line of code and still produce the same results:
[ $PWD = /tmp ] && print "PWD is /tmp" || print
"PWD is NOT /tmp"
NOTE: If you do not understand the use of && and || in this
example, see our tip on Combining
UNIX Commands using && and ||
Running the script produces the following results:
$ pwd
/home/livefire
$ /home/livefire/bin/dir_chk
PWD is NOT /tmp
$ cd /tmp
$ pwd
/tmp
$ /home/livefire/bin/dir_chk
PWD is /tmp
$