Shell Programming Case Study #1
10/30/04
#!/bin/sh
# case study #1: show certain file characteristics in nice columns
# assume we want to output the filename, then owner,
# then size.
# show these in nice columns
# do this for all regular files in the $1 dir and
# all subdir's (recursively)
DIR=$1 # save cmd line arg before using set
USAGE="Usage: `basename $0` directory"
if [ ! -d "$DIR" ]
then
echo "Error: $DIR is not a valid directory" >&2
echo $USAGE >&2
exit 1
fi
echo "Starting dir is $DIR\n"
# show column headings
FNSZ=25
OWNSZ=10
BYTSZ=10
BLOCKSZ=9
printf "%-${FNSZ}s %-${OWNSZ}s %${BYTSZ}s %${BLOCKSZ}s\n\n" "filename" "owner" "bytes" "blocks"
###printf "%-25s %-10s %10s %9s\n\n" "filename" "owner" "bytes" "blocks"
# show data
for FILE in `find $DIR -type f 2>/dev/null`
do
set -- `ls -ld $FILE`
# set will assign values to the positional parameters: $1, $2 etc
# Example output for ls -l:
#
# -rw-r--r-- 1 stevemor instrctr 167 Oct 16 16:06 class1
# $1 $2 $3 $4 $5 $6 $7 $8 $9
#
# Add -- after set or any cmd if first arg might start w/ -
BLOCKS=`echo "scale=2;$5/512"|bc`
printf "%-${FNSZ}s %-${OWNSZ}s %${BYTSZ}d %$BLOCKSZ.2f\n" $9 $3 $5 $BLOCKS
###printf "%-25s %-10s %10d %9.2f\n" $9 $3 $5 $BLOCKS
# Added dash (-) to left justify the filename and owner
# The size in bytes and blocks do not contain a dash (-) so they are
# right justified.
# Right justify (no dash) the sizes since that makes numbers easier
# to compare.
# Each field specification starts with a % sign
# end in s for string
# end in d for decimal integer
# end in f for floating point
# %9.2f reserves 9 char positions
# 2 to the right of the decimal pt
# 1 for the decimal pt itself
# 6 to the left of the decimal pt
# Note: if the actual value exceeds the size specification,
# the whole value will be printed anyway
# so your columns will not line up.
done
Starting dir is /tmp
filename owner bytes blocks
/tmp/daemonstat.any.80 root 3676 7.17
/tmp/daemonstat.any.620 root 3676 7.17
/tmp/f1 stevemor 132 0.25
/tmp/f2 stevemor 94 0.18
/tmp/Ex05831 g4b 0 0.00
/tmp/mori/f1 stevemor 1895 3.70
/tmp/mori/f2 stevemor 41895 81.82
/tmp/Rx05831 g4b 4096 8.00
/tmp/Ex07739 h8j 6144 12.00
/tmp/Rx07739 h8j 3072 6.00
/tmp/pga006lF h8j 959 1.87
/tmp/Ex09097 a8y 6144 12.00
/tmp/Ex16198 h8j 0 0.00
/tmp/Rx09097 a8y 2048 4.00
/tmp/pga002kK h4e 0 0.00
/tmp/hpnpcfg.log root 848 1.65
/tmp/pga002w3 y6g 2180 4.25
/tmp/Ex09263 stevemor 8192 16.00
/tmp/Rx09263 stevemor 3072 6.00
/tmp/dograde3 stevemor 1997 3.90