SIGINT to cancel read in bash script?

后端 未结 2 1193
無奈伤痛
無奈伤痛 2021-01-12 21:48

I\'m writting a bash wrapper to learn some scripting concepts. The idea is to write a script in bash and set it as a user\'s shell at login.

I made a while loop that

相关标签:
2条回答
  • 2021-01-12 22:16

    I know this is old as all heck, but I was struggling to do something like this and came up with this solution. Hopefully it helps someone else out!

    #/usr/bin/env bash
    # Works ok when it is invoked as a bash script, but not when sourced!
    function reset_cursor(){
        echo
    }
    trap reset_cursor INT
    while true; do
        command=$( if read -e -p "> " line ; then echo "$line"; else echo "quit"; fi )
        if [[ "$command" == "quit" ]] ; then
            exit
        else
            history -s $command
            eval "$command"
        fi
    done
    trap SIGINT
    

    By throwing the read into a subshell, you ensure that it will get killed with a sigint signal. If you trap that sigint as it percolates up to the parent, you can ignore it there and move onto the next while loop. You don't have to have reset_cursor as its own function but I find it nice in case you want to do more complicated stuff.

    I had to add the if statement in the subshell because otherwise it would ignore ctrl+d - but we want it to be able 'log us out' without forcing a user to type exit or quit manually.

    0 讨论(0)
  • 2021-01-12 22:19

    You could use a tool like xdotool to send Ctrl-A (begin-of-line) Ctrl-K (delete-to-end-of-line) Return (to cleanup the line)

    #!/bin/bash
    trap "xdotool key Ctrl+A Ctrl+k Return" SIGINT;
    unset command
    while [ "$command" != "quit" ] ;do
        eval $command
        read -e -p "$USER - SHIELD: `pwd`> " command
      done
    trap SIGINT
    

    But I strongly invite you to rtfm... In searching for ``debug'' keyword...

    man -Pless\ +/debug bash
    
    0 讨论(0)
提交回复
热议问题