2015-05-03 18 views
5

我在這裏有一個問題。似乎我的Bash腳本忽略了所有介於dodone之間的內容。不知道爲什麼,也許你會看到問題。提前致謝。bash閱讀用戶y/n回答不起作用(while循環讀取查找輸出內部的讀命令)

katalogas=$1 
find $katalogas -type f -mtime +3 | while read $failai 
do 
read -p "Run command $foo? [yn]" answer 
if [[ $answer = y ]] ; then 
    rm $failai 
fi 
done 
+1

你在哪裏設置'$ failai'? –

+1

'read ... answer'通過stdin從你的「find」命令中讀取, – Cyrus

+1

Michael Jaros,我編輯了我的帖子,現在你會看到我在哪裏使用$ failai :) – semkius

回答

7

嘗試通過

read -p "Run command $foo? [yn]" answer </dev/tty 

更換

read -p "Run command $foo? [yn]" answer 

,以避免從標準輸入讀取。

更新與意志的建議:

katalogas=$1 
read -p "Run command $foo? [yn]" answer 
if [[ $answer = y ]] ; then 
    find "$katalogas" -type f -mtime +3 | while read failai 
    do 
    rm "$failai" 
    done 
fi 
+1

現在它更好,但不是真的我想要的只是一次確認Y,不幸的是,這種方式腳本一直詢問每一個文件 – semkius

+1

然後,您需要將「讀取」代碼移到循環之外,但您沒有真正提供足夠的上下文到腳本的其餘部分發生了什麼,但是您的代碼編寫方式,它會爲我們正在循環的每個文件提出問題。 – Will

+0

非常感謝Cyrus和Will!:) – semkius

1

所以我看到的第一個問題是,你的while read $failai應該是while read failai(不$)。試試這個:

katalogas="$1" 
find "$katalogas" -type f -mtime +3 | while read failai; do 
    read -p "Run command ${foo}? [yn]" answer 
    if [[ "$answer" = "y" ]]; then 
     echo labas 
    fi 
done 

至於提示是或否,不過,我通常使用這樣的事情:

function prompt_yn() 
{ 
    local default="" 
    local prompt="y/n" 
    local input 

    # If $2 specifies a default choice, configure options accordingly. 
    if [[ "${2:-}" = "Y" ]]; then 
     prompt="Y/n" 
     default="Y" 
    elif [[ "${2:-}" = "N" ]]; then 
     prompt="y/N" 
     default="N" 
    fi 

    # Prompt the user until they give an appropriate answer. 
    while true; do 
     read -p "$1 [${prompt}] " input 
     [[ -z "$input" ]] && input="$default" 

     case "$input" in 
      [Yy]*) return 0;; 
      [Nn]*) return 1;; 
      *) echo "Please answer yes or no.";; 
     esac 
    done 
} 

所以,如果你使用上面的代碼,你的代碼應該是這樣的:

katalogas="$1" 
find "$katalogas" -type f -mtime +3 | while read failai; do 
    if prompt_yn "Run command ${foo}?"; then 
     echo labas 
    fi 
done 

您還可以添加一個"Y""Run command ${foo}?""N"指定一個默認值,如果用戶只是按下Ë nter

編輯:似乎我錯過了關於這一部分的觀點。 Cyrus's answerread不能在循環內工作的解決方案。 This StackOverflow post也解釋得很好。然而,根據你的評論@semkius,似乎你只想在循環之外提問一次。

+1

您的'prompt_yn'是真的很好,但它有點在這個問題的背景中忽略了這一點。它不能像OP的代碼那樣解決從管道中讀取的問題(檢查Cyrus的答案)。 –

+0

我不認爲賽勒斯的回答解決了這個問題。讀取的塊沒有被輸入,因爲他在'while read'的變量名之前放了'$'。由於他沒有引用它或任何其他內容,它只是評估爲「while ',導致循環不發生。我從來沒有見過將'/ dev/tty'重定向到讀取中,'stdin'在這裏有什麼問題? – Will

+1

你對這個陳述是正確的,可能沒有做OP的意圖,但這並不能阻止循環。請參閱'help read':「如果未提供名稱,則讀取的行會存儲在REPLY變量中。」 –

0

使用命令reset 然後執行你的shell腳本。