2

I'm searching for a way to catch the value of function keys in a variable, when a user push the function key. I have tried with dd command but only the letters or numbers keys are trapped: dd command doesn't work why the function keys.

Here ae several tests lines I have tried but the variable always return nothing with function keys :

selection=dd if=/dev/tty bs=2 count=2 2>/dev/null

selection=$(dd bs=2 count=2 2>/dev/null)

selection=dd bs=1 count=1 2>/dev/null

selection=$(dd bs=1 count=1 2>/dev/null)

selection=head -c1

selection=$(head -c1)

For example - when I push F3 key, value ^[[13~ appears on screen but when doing echo selection=$selection, my variable "selection" remains empty (selection=)

  • when I push d key, value d appears on screen and when doing echo selection=$selection, my variable "selection" equal (selection=d)

Can someone help me? What am I doing wrong? Why doesn't it work with function keys (F3...)?

Thank you

  • Might try the Unix stack exchange. – pbhj Mar 18 at 19:25
  • is it resolved ? – cmak.fr Mar 19 at 12:26
1

You can do like this:

  • Read code of keys
    Press Ctrl+v and press a key. F1 for example
    And read the output. F1 gives ^[OP
    Note that ^[ is for Escape that you will write in a script as \e

  • Or get all codes of functions keys
    for x in {1..24}; do echo -n "F$x "; tput kf$x | cat -A; echo; done
    Assuming F13 is Shift + F1

  • Handle keys in script
    With bash functions like while, read, case / esac

Example:

#!/bin/bash

ReadKey() {
  if read -sN1 KEY; then
    while read -sN1 -t 0.001 ; do
      KEY+="${REPLY}"
    done
  fi
}

while ReadKey; do
  case "${KEY}" in
    $'\eOP')   echo 'F1';;
    $'\e[24~') echo 'F12';;
    *) echo    "Keys pressed: ${KEY}";;
  esac
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.