【问题标题】:UNIX shell scripting if and grep command settingUNIX shell 脚本 if 和 grep 命令设置
【发布时间】:2016-08-27 18:55:20
【问题描述】:

设计一个接受输入字符串(州名)的 shell,并查找该州的所有大学。如果找到,则显示所有大学作为输出,否则显示错误消息,如“文件中未找到 xxx”。这里 xxx 是输入字符串。 (提示:这可以通过将搜索结果重定向到一个文件然后检查该文件是否为空来完成)。例如,如果输入字符串是“NSW”,则输出应该是新南威尔士州所有大学的列表。如果输入为“AUS”,则应显示一条错误消息,指出“在文件中未找到 AUS”。

这是我的代码:

#!/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

即使我输入的字符串在文件中找不到,也不会弹出错误的语句。不知何故,真正的陈述被粗略地执行了。

【问题讨论】:

  • 再次检查 if 语句检查的内容。
  • 请看:shellcheck.net
  • 请注意,您可以使用:if [ -z "$State" ]; then echo "You didn't type a state abbreviation" >&2; elif ! grep "$State" Aus-Uni.txt; then echo "$State was not found in the file Aus-Uni.txt" >&2; fi ... 报告标准错误,并在未找到 AUS 时发现,以及其他改进。仅当给定名称为空时才报告未找到状态 - 与请求的名称不完全一致。
  • 为什么将状态作为输入而不是参数?只需将其作为参数传递,您的整个脚本就会变为 grep "$1" Aus-Uni.txt || echo "$1 was not found in Aus-Uni.txt" >&2
  • 当您通过-n $State 测试并执行grep 时,将无法到达属于-n $State 测试的else 代码。请在$State周围加上引号。

标签: bash unix grep


【解决方案1】:

首先,您无法检查用户输入是否符合您的要求,即全部大写。

您可以在处理之前使用[ shell param expansion ] 将输入转换为全大写,例如:

echo "Please enter State of Uni (e.g NSW)"
read State
State="${State^^}" # Check ${parameter^^pattern} in the link

改变

if [ -n $State ]

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

【讨论】:

  • OP 不能使用${State^^},因为#! 行说sh,而不是bash(即使问题被标记为bash)。 grep -i 而不是?
【解决方案2】:

这只检查字符串是否为非空

[[ -n $State ]]

如果检查成功则运行 grep - 但不检查 grep 是否成功

试试这个

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

【讨论】:

  • hmm,也提一下引入[[..]]的原因:)
  • 错误信息应该发送到标准错误,而不是标准输出
猜你喜欢
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多