I would like to assign a bash script to a keyboard key in Linux to toggle between multiple commands. I've researched the problem and came across the following bash script:
#!/bin/sh
TOGGLE=$HOME/.toggle
if [ ! -e $TOGGLE ]; then
touch $TOGGLE
command1
rm $TOGGLE
command2
fi
The problem is I don't know how to modify the script to add a third or fourth command. I'm actually trying to answer this question, I think this is the way to go for him.
How do I toggle among multiple commands in the script?
You need more than a simple toggle (which only has two states); you need a file that contains a value that you update. A simple 4-state example:
# Script that rotates between English, Russian, French, and Finnish keyboards
# Name of the state file
state_file=$HOME/.keyboard_state
# Ensure that the state file exists; initialize it with 0 if necessary.
[ -f "$state_file" ] || printf '0\n' > "$state_file"
# Read the next keyboard to use
read state < "$state_file"
# Set the keyboard using the current state
case $state in
0) setxkbmap en ;;
1) setxkbmap ru ;;
2) setxkbmap fr ;;
3) setxkbmap fi ;;
esac
# Increment the current state.
# Could also use state=$(( (state + 1) % 4 ))
state=$((state + 1))
[ "$state" -eq 4 ] && state=0
# Update the state file for the next time the script runs.
printf '%s\n' "$state" > "$state_file"
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.