Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Shell Scripting - detect the Enter key

Tags:

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

like image 355
veda Avatar asked Apr 10 '10 04:04

veda


People also ask

How do you send enter key in Expect script?

hence typing "\r" for "Enter" key action.

What is $@ in bash script?

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.

What is $_ in bash?

$_ (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.


2 Answers

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 
like image 88
Mark Rushakoff Avatar answered Oct 19 '22 00:10

Mark Rushakoff


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 
like image 27
tsds Avatar answered Oct 19 '22 00:10

tsds