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 forread
prevents special handling of backslash (\
) characters. - The
-N
(instead of-n
) option forread
prevents special handling of delimiter characters (including space and newline). $'\n'
is Bash ANSI-C Quoting.- I used
case
instead ofif
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