簡體   English   中英

UNIX Shell腳本if和grep命令設置

[英]UNIX shell scripting if and grep command setting

設計一個外殼程序,該外殼程序接受狀態名稱的輸入字符串,並查找處於該狀態的所有大學。 如果找到,它將顯示所有大學作為輸出,否則將顯示錯誤消息,例如“在文件中未找到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

即使在文件中找不到我輸入的字符串,也不會彈出錯誤語句。 某種程度上說,真實的語句可以粗略地執行。

首先,您無法檢查用戶輸入是否符合要求全部大寫的要求。

您可以使用[shell參數擴展]在處理之前將輸入轉換為全部大寫,例如:

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

這只會檢查字符串是否為非空

[[ -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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM