Note: The following material was developed by Claude Cantin of the Research Computing Support Group of the National Research Council of Canada, and is used with his permission.

Your Name Here

basename: Current Directory

basename directory
returns the portion of directory after the last ``/", i.e. the current directory name.

For example,

#!/bin/sh
CUR_DIR=`basename \$cwd`
will set CUR_DIR to be the current directory name from the last ``/" to the end (if the current directory is /usr/people/cantin, it would return cantin).


dirname: Directory Path

dirname directory
will return the path of the current directory from the beginning of the directory name to the last ``/".

For example,

dirname /usr/people/cantin
will return /usr/people. But
dirname cantin
will return . (dot).

For example, the following script will take as its first parameter, the name of a directory, and return its absolute path name. The directory must be given either as a relative or absolute path name.

#!/bin/sh 
# Returns full path name of a directory.
if [ $# -ne 1 ]
then
    echo " "
    echo " $0: must have one parameter."
    echo " "
    exit
fi

C_DIR=`pwd`
if test "`dirname $1`" = "."
then
    FULL_NAME=$C_DIR/$1
else
    FULL_NAME=$1
fi
echo "Absolute path name is $FULL_NAME."


stty -echo: Passwords

If the script requires the input of a ``secret" string, the string typed from the keyboard should not be displayed on the screen. To stop the display of the characters typed,

stty -echo
may be used.

To resume echoing of the characters,

stty echo
is used.

#!/bin/sh
echo "Please enter your passcode: \c"
stty -echo
read PASSCODE
stty echo
echo "The passcode was not seen when typed."


cut, awk: Cut Selected Fields

cut and awk may both be used to select a specific field from the output of a command. A typical application would be to create a list of currently logged-in users:

#!/bin/sh
#
# using cut:
USERS=`who | cut -f1 -d" "`
echo "Users on the system are: $USERS."

# using awk:
USERS=`who | awk '{print $1}'`
echo "Users on the system are: $USERS."

In the first example, cut takes its input from the who command. -f1 specifies that the first field is to be cut out from each line, and -d" " specifies that the field delimiter is a space.

In the second example, awk takes its input the same way cut did, then prints the first field (space is the default field delimiter for awk).

In general, cut is a much simpler command to use. awk is a full language; scripts can be written using awk as the language instead of the shell script.