簡體   English   中英

Bash Shell 腳本 - 檢測 Enter 鍵

[英]Bash Shell Scripting - detect the Enter key

我需要將我的輸入與Enter / Return鍵進行比較...

read -n1 key
if [ $key == "\n" ]
   echo "@@@"
fi

但這不起作用..這段代碼有什么問題

發布的代碼有幾個問題。 內聯注釋詳細說明了要修復的內容:

#!/bin/bash 
# ^^ Bash, not sh, must be used for read options

read -s -n 1 key  # -s: do not echo input character. -n 1: read only 1 character (separate with space)

# double brackets to test, single equals sign, empty string for just 'enter' in this case...
# if [[ ... ]] is followed by semicolon and 'then' keyword
if [[ $key = "" ]]; then 
    echo 'You pressed enter!'
else
    echo "You pressed '$key'"
fi

在進行比較之前定義空的 $IFS(內部字段分隔符)也是一個好主意,否則你最終可能會得到 " " 和 "\\n" 相等。

所以代碼應該是這樣的:

# for distinguishing " ", "\t" from "\n"
IFS=

read -n 1 key
if [ "$key" = "" ]; then
   echo "This was really Enter, not space, tab or something else"
fi

如果有人想要使用包含倒計時循環的此類解決方案,我將添加以下代碼僅供參考。

IFS=''
echo -e "Press [ENTER] to start Configuration..."
for (( i=10; i>0; i--)); do

printf "\rStarting in $i seconds..."
read -s -N 1 -t 1 key

if [ "$key" = $'\e' ]; then
        echo -e "\n [ESC] Pressed"
        break
elif [ "$key" == $'\x0a' ] ;then
        echo -e "\n [Enter] Pressed"
        break
fi

done

read從標准輸入讀取一行,直到但不包括行尾的新行。 -n指定最大字符數,如果達到該字符數,則強制read提前返回。 然而,當按下回車鍵時,它仍然會提前結束。 在這種情況下,它返回一個空字符串 - 直到但不包括Return鍵的所有內容。

您需要與空字符串進行比較,以判斷用戶是否立即按下Return

read -n1 KEY
if [[ "$KEY" == "" ]]
then
  echo "@@@";
fi

這些條件都不適合我,所以我想出了這個:

${key} = $'\0A'

在 CentOS 上使用 Bash 4.2.46 進行測試。

暫無
暫無

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

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