Bash Shell Scripting - detect the Enter key

前端 未结 5 1498
时光取名叫无心
时光取名叫无心 2020-12-14 02:21

I need to compare my input with Enter/Return key...

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

But this

5条回答
  •  -上瘾入骨i
    2020-12-14 02:53

    Several issues with the posted code. Inline comments detail what to fix:

    #!/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
    

提交回复
热议问题