简体   繁体   English

UNIX Shell脚本if和grep命令设置

[英]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”. 如果找到,它将显示所有大学作为输出,否则将显示错误消息,例如“在文件中未找到xxx”。 Here xxx is the input string. xxx是输入字符串。 (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. 例如,如果输入字符串为“ NSW”,则输出应为新南威尔士州所有大学的列表。 If the input is “AUS”, an error message should be displayed, saying that “AUS was not found in the file”. 如果输入为“ AUS”,则应显示一条错误消息,指出“在文件中未找到AUS”。

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 : 您可以使用[shell参数扩展]在处理之前将输入转换为全部大写,例如:

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 如果检查成功,则grep会运行-但是不会检查grep的成功

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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