Home > Back-end >  How to know difference between [ENTER] and [SPACE] in bash
How to know difference between [ENTER] and [SPACE] in bash

Time:06-08

I want to make a script that functions differently when pressed [Space] and differently when pressed [Enter] .

what i tried:

#!/bin/bash

read -n1 Input

if [[ $Input == \n ]]; then
    echo "Enter is Pressed"
elif [[ $Input == "" ]]; then
    echo "Space is pressed"
fi

Any suggestions or advice is very helpful. Thanks

CodePudding user response:

Try this Shellcheck-clean code:

#! /bin/bash

read -r -N1 Input

case $Input in
    $'\n')  echo "Enter is Pressed";;
    ' ')    echo "Space is pressed";;
esac
  • The -r option for read prevents special handling of backslash (\) characters.
  • The -N (instead of -n) option for read prevents special handling of delimiter characters (including space and newline).
  • $'\n' is Bash ANSI-C Quoting.
  • I used case instead of if just because it's a bit less verbose in this example.

CodePudding user response:

read -N 1 input
echo 
if [[ "$input" == $'\x0a' ]]; then
   echo "Enter is Pressed" 
elif [[ "$input" == $'\x20' ]]; then
   echo "Space is Pressed" 
else
   echo "'$input' is Pressed" 
fi
  • Related