Reputation: 1
To design a shell that accepts an input string which is a state name, and looks for all the universities that are in that state. If found, it displays all the universities as output, otherwise it displays an error message like “xxx was not found in the file”. Here xxx is the input string. (Hint: This can be done by redirecting the search results to a file and then checking whether the file is empty or not). For example, if the input string is “NSW”, the output should be a list of all the universities in NSW. If the input is “AUS”, an error message should be displayed, saying that “AUS was not found in the file”.
Here is my code:
#!/bin/sh
echo "Please enter State of Uni (e.g NSW ; NAME MUST BE UPPER CASE)"
read State
if [ -n $State ]
then
grep "$State" Aus-Uni.txt
else
echo "$State was not found in the file"
fi
exit
There is no false statement popping up even the string that I entered was not found in the file. Somehow the true statement is roughly executed.
Upvotes: 0
Views: 558
Reputation: 827
This only checks whether the string is nonempty
[[ -n $State ]]
The grep runs if the check succeeds - but the success of grep is not checked
Try this
if [[ -n $State ]]; then
if ! grep "$State" Aus-Uni.txt; then
echo "$State was not found in the file"
exit 2
fi
else
echo "State is empty"
exit 1
fi
Upvotes: 2
Reputation: 21965
Firstly, you've no way to check whether the user input is compliant with your requirement that it should be all upper-case.
You could use [ shell param expansion ] to convert the input to all-uppercase before processing, well, something like :
echo "Please enter State of Uni (e.g NSW)"
read State
State="${State^^}" # Check ${parameter^^pattern} in the link
Change
if [ -n $State ]
to
if [ -n "$State" ]
# You need to double-quote the arguments for n to work
# You can't use single quotes though because variable expansion won't happen inside single quotes
Upvotes: 2