Determine if F1 key is pressed in Bash script.

Hi, I'm trying to determine if a Function key (F1)  has been pressed.

Using - dumpkeys - I know the key code for F1 is "\033[[A"

Now, I write a bash script like this

#!/bin/sh
echo please enter the F1 function key
read -sn3 key
if [ $key == "\033[[A" ]; then
        echo you pressed the F1 key
        else
        echo you pressed some other key
fi

But this dosen't work. Can someone tell me how to do this proper.
Thanks


AirgazmAsked:
Who is Participating?
 
dimitryConnect With a Mentor Commented:
This code is working:
--------------------------------------------------------------------------------
#!/bin/sh
f1='\[\[A'
f2='\[\[B'
SUCCESS=0
echo please enter the F1 function key
read -n4 key                      # Read 4 characters.
echo -n "$key" | grep "$f1"  #Check if character code detected.
if [ "$?" -eq $SUCCESS ]
then
  echo "F1 key pressed."
  exit $SUCCESS
fi
echo -n "$key" | grep "$f2"  #Check if character code detected.
if [ "$?" -eq $SUCCESS ]
then
  echo "F2 key pressed."
  exit $SUCCESS
fi
0
 
MysidiaCommented:
well ^[[[A is 4 characters.

But if the user presses something else it will only be one character.
Perhaps

read -sn1 key
if [ $key == "\033" ] ; then
     read -sn3 key
     if [ $key == "[[A" ] ; then
          echo "You pressed the F1 key"
     else
          echo "You pressed some other key"
     fi
else
  echo "You pressed some other key"
fi
0
 
AirgazmAuthor Commented:
Did you try that on your system? It dosen't work correctly here.

I'm pretty sure a function key is actually 3 keys but I could be wrong.  

If I do a simple command on prompt

read key
when I press the F1 key it returns ^[[A  - 3 chars plus the esc

I have looked on the net for an answer and have found nothing covering how Linux returns these special codes with a read function.



0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
AirgazmAuthor Commented:
Hmm, that code dosen't work correctly either.  

It didn't print anything other than the char input "^[[A" and then a ~







0
 
AirgazmAuthor Commented:
Opps I meant char input "^[[11~"  

0
 
dimitryCommented:
It is working on my RH 9.0 machine...
Are you sure you took the code as is ?
0
 
AirgazmAuthor Commented:
Ok, you were right, I was using Putty and it wasn't set to Linux mode, I changed it and now it works.  
Seems like the code could be more simple but it does what it is suppose to do.

Thanks
0
 
dimitryCommented:
You are welcome
0
All Courses

From novice to tech pro — start learning today.