简体   繁体   中英

UNIX shell scripting if and grep command setting

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM