簡體   English   中英

While循環不遍歷文件

[英]While loop not iterating through file

我正在嘗試將ID添加到文件中。 該文件如下所示:

field1:field2:field3:field4

我想檢查第二個字段是否已經存在(向用戶輸出消息)或不存在(一旦我從用戶那里獲得更多信息,就將其添加到文件中)。 我編寫了一個循環來完成此操作,但是每當我運行腳本的這一部分時,它就會滯后並且永遠不會執行。 我認為問題是我的while循環無法正確捕獲每一行。

 40 checkID()
 41 {
 42 
 43     local input
 44     local line
 45     while : ; do
 46         read -p "Enter id (or ENTER to quit):" input
 47         [ -z "$input" ] && return 1
 48         while read line; do
 49                 if ! grep -q "$(cut -d: -f2)" "$file"; then
 50                         echo "$input"
 51                 else    
 52                         error "id '$input' already exists in the file"
 53                 fi
 54         done
 55     done
 56 }

您根本不希望在其中進行while read循環,並且您希望cut從文件而不是從用戶讀取。

要在文件的第二列中查找內容,可以使用

if cut -d: -f2 "$file" | grep -q "$input"
then
    echo "Found it"
fi

另請注意,這是一個子字符串匹配項,因此,如果輸入為“ foo”,則它將匹配第二個字段為“ food truck”的文件

暫無
暫無

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

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