Bash Shell Scripting - detect the Enter key

前端 未结 5 1495
时光取名叫无心
时光取名叫无心 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条回答
  • 2020-12-14 02:35

    Also it is good idea to define empty $IFS (internal field separator) before making comparisons, because otherwise you can end up with " " and "\n" being equal.

    So the code should look like this:

    # 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-14 02:54

    I'm adding below code just for reference if someone will want to use such solution containing countdown loop.

    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
    
    0 讨论(0)
  • 2020-12-14 02:57

    read reads a line from standard input, up to but not including the new line at the end of the line. -n specifies the maximum number of characters, forcing read to return early if you reach that number of characters. It will still end earlier however, when the Return key is pressed. In this case, its returning an empty string - everything up to but not including the Return key.

    You need to compare against the empty string to tell if the user immediately pressed Return.

    read -n1 KEY
    if [[ "$KEY" == "" ]]
    then
      echo "@@@";
    fi
    
    0 讨论(0)
  • 2020-12-14 02:57

    None of these conditions worked for me and so I've came up with this one:

    ${key} = $'\0A'
    

    Tested on CentOS with Bash 4.2.46.

    0 讨论(0)
提交回复
热议问题