简体   繁体   中英

Define a short cut for a shell script

How can I define a shortcut for a shell script and when that script is started, hitting that shortcut will interrupt that script or the action I want to take in that script?

One thing you could do is read inputs in a while loop

#!/usr/bin/env bash
runmain(){
    trap 'return' SIGINT # Stops Ctrl+C exiting, instead returns
    while((i++<=10)); do
        echo "Main function, pressing Ctrl+C will return to input menu, loop ${i}"
        sleep 3
    done
}

while true; do
    echo 'Input m to run main, or q to quit'
    read -rsn1 input
    echo "You pressed ${input}"
    case "${input}" in
        m) runmain; trap 'exit' SIGINT ;;
        q) exit ;;
        *) # default case, do nothing ;;
    esac
done

So pressing m will run the main function, Ctrl+C to break out of it, and q or Ctrl+C again to exit the script. Another good option would be to use the dialog utility.

And a good way to find keycodes is, when in your terminal, press the Insert key, and then the key you want to find the name of. So Insert+LeftArrow prints

^[[D

Then in the case statement, you would write

D) command ;;

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