Im in a intro to unix class and we have to create a a basic program to look up an argument in a large file.
when no argument is given he wants us to produce a error messgae, well this works but it also produces another error message because my variable now equals nothing.
#! /bin/bash
let num=$*
if [[ $num -gt 99 && $num -lt 1000 ]]
then
echo Area Codes for '"'$num'"':
grep "^$num" ~cs155/pub/area-codes | sed 's/^/ /'
elif [[ $num -lt 1 ]]
then
echo 'usage: ./area <query> ...' | grep usage
else
echo good night
fi
when ./area 303 is entered it works perfectly but when just ./area is entered i get this error
./area: line 2: let: num=: syntax error: operand expected (error token is "=")
usage: ./area <query> ...
the second line is my own error message which i want how do i get rid of the first?
You may consider restructuring the script to separate the parameter validation from the processing such that the script has a beginning a middle and an end.
The actual error is caused by trying to use $num which has no value. We can prevent this by checking the value of $# first. Because there is more than one reason to reject the command line we can prepare the "usage" string in advance. In the original script the "|grep usage" has no use .
Just as an aside, your shebang line contains a lot of trailing blanks and an extra blank between the hash and /bin/bash.
#!/bin/bash
argcount=$# # Number of arguments
num="$1" # Value of parameter 1
usage='usage: ./area <query> ...' # Usage string
######################
# Parameter validation
######################
if [ ${argcount} -ne 1 ]
then
echo "${usage}"
exit
fi
#
if [[ $num -gt 99 && $num -lt 1000 ]]
then
:
else
echo "${usage}"
exit
fi
########################
# Processing starts here
########################
echo Area Codes for '"'$num'"':
grep "^$num" ~cs155/pub/area-codes | sed 's/^/ /'
########
# End
########
echo "good night"