Bash:在 while read 迴圈中讀取輸入不起作用

Bash:在 while read 迴圈中讀取輸入不起作用

在 while read 迴圈內讀取輸入似乎不起作用

while read line
do
 echo "get some input from the user"
 read response
done < some_file.txt

執行不會像讀取在循環之外那樣暫停。為什麼是這樣?是否有在 while read 迴圈中讀取輸入的解決方法?

答案1

問題是read line和都read response期望(並獲取)來自 的數據stdin
這個問題on SO 解釋了其中的一些內容,並提供了更多資訊的連結。

太長了;博士
接受的答案顯示:

從控制終端設備讀取:read input </dev/tty

答案2

讓內部讀取指令使用 stdin,並在 while 迴圈中使用不同的檔案描述符

while read -u 3 line; do
  read -p "get some input from the user" response
done 3< some_file.txt

答案3

謝謝尼夫!也要感謝 bgStack。經過幾個小時的搜索,我終於得到了答案!太棒了!我使用“echo $(tty)”來檢測我的終端路徑,或者您只需將其作為變數即可。對我來說這是另一個用例。 U 正在讀取一個檔案並想確認執行情況。也許下面的例子可以幫助其他人。

#!/bin/bash

export terminal=$(tty)

cat file | while read val1 val2
do
   while true; 
            do
              read -p "would you like to XYZ" yn
              case $yn in
                        [Yy]* )     echo "# Move $val1 to $val2        #";break;;
                        [Nn]* )     echo "#---------no action----------#";break;;
                        * )         echo "# Please answer yes or no.   #";;
              esac
            done < $terminal
done

答案4

尼夫說得完全正確。但是,當您使用多個終端時,您需要具體化。

對於那些來自谷歌的人,恭喜你找到這個頁面。如果您需要在 while read 迴圈期間執行任何使用者輸入(包括rm -iread或其他任何內容),您可以指定要使用的輸入管道。

這是我使用的該解決方案的一個片段:

#in declarations
thistty=$(tty)

lsuser -R LDAP -a home pgrp ALL 2>/dev/null | while read line
do
   homedir=$(echo $homedir | awk -F= '{print $2}')
   sudo rm -ir "$homedir" < $thistty
done

相關內容