I wrote a bash script to print contents of files in a given directory in a loop.
How can I improve command line parameters handling to the script? I feel the parameter processing as of now uses too much code and it is quite clumsy. I think I had to write too much code to validate the the option arguments are numeric.
The script takes either -c numeric_choice_id
and/or -l time_in_seconds
and keep printing the contents of the files.
- only
-c
number: it cats the file and ends - only
-l
number: repeatedly cats all the files -c num1
and-l num2
: repeatedly cats that particular file everynum2
seconds
#!/bin/bash
SYSPATH="$PWD/"
FILES="$PWD/file1
$PWD/file2
$PWD/file3"
count=0
for i in $FILES
do
(( count++ ))
menu="${menu}\n${count}. `basename $i`"
list="${list} `basename $i`"
done
testNumeric()
{
if ! echo "$1" | grep -q '^[0-9]\+$'
then
echo "$0 Non numeric argument supplied to choice or time"
exit
fi
}
usage()
{
echo -e "`basename $0` -c numeric_choice [ -l time in seconds ]\n
-c numeric id for the choice
-l print o/p every time seconds
-h print this menu
choice could be: \n$menu"
exit
}
# Test if any arguments have been provided
if [ "x$1" = "x" ] || [ "$1" = "-h" ]
then
usage
fi
# Allow getopt to parse the options and report error if needed
args=`getopt "c:l:" "$@"`
if [ "$?" -ne "0" ]
then
usage
fi
# Set positional parameters
set -- $args
for i;
do
case "$i" in
-c )
choice=$2
testNumeric $choice
shift
shift ;;
-l ) repeatTime=$2
testNumeric "$repeatTime"
shift
shift ;;
-- )
break ;;
esac
done
[ "x$choice" = "x" ] && choice=`seq $count`
[ "x$repeatTime" = "x" ] && repeatTime=0
set -- $list
while [ true ]
do
if [ "$repeatTime" = "0" ]
then
for a in $choice
do
eval temp=\${${a}}
cat $SYSPATH${temp}
done
break;
else
for a in $choice
do
eval temp=\${${a}}
cat $SYSPATH${temp}
done
sleep $repeatTime
fi
done