简体   繁体   中英

Linux Script to execute something when F1 is hitter

I have this script start.sh

 #!/bin/bash
while[1]
do 
read -sn3 key
if [$key=="\033[[A"]
then
  ./test1
else
  ./test2
fi
done

I want to set up a forever loop check see if F1 key pressed. If pressed execute test1 else test2. I did start.sh & running in background so other programs can run.

I got error while [1] command not found syntax error near unexpected token 'do' [f==\\033]: command not found

Also where is this read command located? I type which read, it didn't find it.

Also, if try ./start.sh & it gives totally different behavior. I enter a key and it says that key is not found. I though & just run the script at background

There are several basic syntax problems in your code (consider using shellcheck before posting to clean up these things), but the approach itself is flawed. Hitting "q" and "F1" produces different length inputs.

Here's a script relying on the fact that escape sequences all come in the same read call, which is dirty but effective:

#!/bin/bash
readkey() {
  local key settings
  settings=$(stty -g)             # save terminal settings
  stty -icanon -echo min 0        # disable buffering/echo, allow read to poll
  dd count=1 > /dev/null 2>&1     # Throw away anything currently in the buffer
  stty min 1                      # Don't allow read to poll anymore
  key=$(dd count=1 2> /dev/null)  # do a single read(2) call
  stty "$settings"                # restore terminal settings
  printf "%s" "$key"
}

# Get the F1 key sequence from termcap, fall back on Linux console
# TERM has to be set correctly for this to work. 
f1=$(tput kf1) || f1=$'\033[[A' 

while true
do
  echo "Hit F1 to party, or any other key to continue"
  key=$(readkey)
  if [[ $key == "$f1" ]]
  then
    echo "Party!"
  else
    echo "Continuing..."
  fi
done

Try this:

#!/bin/bash

while true
do 
  read -sn3 key
  if [ "$key" = "$(tput kf1)" ]
  then
    ./test1
  else
    ./test2
  fi
done

It is more robust to use tput to generate the control sequence, you can see a full list in man terminfo . If tput isn't available, you can use $'\\eOP' for most terminal emulators or $'\\e[[A' for the Linux console (the $ is necessary with the string to make bash interpret escape sequences).

read is a bash builtin command - try help read .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM