簡體   English   中英

Bash 讀取用戶 y/n 答案不起作用(循環讀取查找輸出中的讀取命令)

[英]Bash reading users y/n answer does not work (read command inside while loop reading find output)

我這里有問題。 似乎我的 Bash 腳本忽略了dodone之間的所有內容。 不知道為什么,也許你會看到問題。 提前致謝。

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

嘗試更換

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

經過

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

避免從標准輸入讀取。

更新 Will 的建議:

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

所以我看到的第一個問題是你的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

您還可以在"Run command ${foo}?"后添加"Y""N" "Run command ${foo}?" 如果用戶只是按Enter ,則指定默認值。

編輯:看來我錯過了關於這一點的一部分。 賽勒斯的回答是解決read在循環內不起作用的問題。 這個 StackOverflow 帖子也很好地解釋了它。 但是,根據您的評論@semkius,您似乎只想在循環之外問一次問題。

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

暫無
暫無

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

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