Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

testing type and number of arguments/options

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
i'm trying this script and have a few basic(stupid) questions.

well the script runs like this.

printfiles [[-s number][-n number2]] filename1 [filename2...]

where number2 is the number of lines to be displayed beginning at line number number1. if one is not present a value of one is assumbed. if number2 is not present, a value of 5 is assumed if neither are present then print lines 1 to 5.

this is where i get confused how do i test how many arguments are assumed and if they are present with the right options.

i'm thining if the user doesn't enter filename arguments or options or different options this will not work and will mess up. how do i test for this?
 
Hi,

This is an example for your printfiles script.
You can also get the options with the getopts function or command (depending on your Os and shell).


printfiles

#
# Usage
#

Usage() {
[ $# -gt 0 ] && echo "$0 - $*"
cat <<-EOD

Usage: $0 [-s number1] [ -n number2] filename1 [filename2...]

-s number1 Starting line
-n number2 Number of lines to display
filename1 ... Files to print

EOD
exit
}

#
# Initialisations, default options
#

StartLine=1
LineCount=5
FileCount=0

#
# Get options
#

while [ $# -gt 0 ]
do
opt=$1
arg=$2
case $opt in
-h)
Usage
;;
-s)
[ -z &quot;$arg&quot; ] && Usage &quot;Missing start line value&quot;
expr &quot;$arg&quot; : &quot;[1-9][0-9]*&quot; > /dev/null || Usage &quot;Start line value not numeric : $arg&quot;
StartLine=$arg
shift
;;
-n)
[ -z &quot;$arg&quot; ] && Usage &quot;Missing lines count value&quot;
expr &quot;$arg&quot; : &quot;[1-9][0-9]*&quot; > /dev/null || Usage &quot;Lines count value not numeric : $arg&quot;
LineCount=$arg
shift
;;
-*)
Usage &quot;Invalid option&quot;
;;
*)
break
;;
esac
shift
done

#
# Get file list
#

[ $# -eq 0 ] && Usage &quot;No file to print&quot;
FileCount=$#

#
# Print files
#

while [ $# -gt 0 ]
do
File=$1
if [ -r &quot;$File&quot; ]
then
echo &quot;----- $File -----&quot;
tail +${StartLine} $File | head -${LineCount}
else
echo &quot;$0 - Invalid file : $File&quot;
fi
echo
shift
done

----------
Jean Pierre.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top