I need to compare my input with Enter/Return key...
read -n1 key if [ $key == "\n" ] echo "@@@" fi
But this is not working.. What is wrong with this code
hence typing "\r" for "Enter" key action.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With