Cover V02, I06
Article
Listing 1
Listing 2
Listing 3
Listing 4
Listing 5
Listing 6

nov93.tar


Listing 3: dirmnu

######################################################################
#
#  dirmnu
#
#  usage:  dirmnu <title> <prompt> <dir> "pattern"
#
#       "dirmnu" lists the contents of a directory that match patterns
#  and allows the user to select one by entering a number.
#       Typical application is in a shell script, using the
#  back-quote mechanism, as in:
#
#  file=`dirmnu "Here are the files" "Select one" . "*.txt"`
#

############################################################
#
#  initialize variables, verify & extract parameters
#
LOCALCMDS=/usr/local
[ $# != 3 -a $# != 4 ] &&
echo "dirmnu: usage: dirmnu <title> <prompt> <dir> <pattern>" >&2
&& exit
title=$1
prompt=$2
dir=$3
shift 3
pattern=$*
[ "$pattern" = "" ] && pattern="*"

#
#  print the title
#
clear       >&2
echo        >&2
echo $title >&2
echo        >&2

#
#  list the files, numbered, and in columns
#
cd $dir
#
#first check to see that files exist
#
count=`ls -d $pattern 2>/dev/null | wc -l`
if [ $count -eq 0 ]; then
echo                               >&2
echo "***NO ITEMS AVAILABLE***"    >&2
echo                               >&2
echo "Press <Return> to ABORT..."  >&2
read dummy                         >&2
echo "ABORT"
exit
fi
# now figure the number of columns
maxlen=`ls -d $pattern 2>/dev/null |
awk  'BEGIN          {max=8}
length($0)>max {max=length($0)}
END            {print max}'     `
colwidth=`expr $maxlen + 5`
numcol=`expr 80 / $colwidth`

ls -d $pattern |
awk '{print " " $0}' |
pr -t -n\)2 -w80 -$numcol -i" "1 >&2 2>/dev/null

#
#  get the user's choice
#
num_files=`ls -d $pattern | wc -l`    #  count the # of files

echo >&2
choice=`getnum 1 $num_files "$prompt"`

[ "$choice" = ABORT ] && echo "ABORT" && exit

####################
#
#  extract the filename from the directory listing
#
chosen_file=`ls -d $pattern | head -$choice | tail -1`
[ ! -r $chosen_file ] &&
echo "dirmnu:  File does not exist or unreadable" >&2 &&
echo "ABORT" && exit
#
#  return the filename on stdout
#
echo $chosen_file