BASH - using trap ctrl+c

前端 未结 2 1039
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 15:24

I\'m trying to execute commands inside a script using read, and when the user uses Ctrl+C, I want to stop the execution of the command, but not exit th

相关标签:
2条回答
  • 2020-12-14 15:48

    You need to run the command in a different process group, and the easiest way of doing that is to use job control:

    #!/bin/bash 
    
    # Enable job control
    set -m
    
    while :
    do
        read -t 10 -p "input> " input
        [[ $input == finish ]] && break
    
        # set SIGINT to default action
        trap - SIGINT
    
        # Run the command in background
        bash -c "$input" &
    
        # Set our signal mask to ignore SIGINT
        trap "" SIGINT
    
        # Move the command back-into foreground
        fg %-
    
    done 
    
    0 讨论(0)
  • 2020-12-14 16:02

    Use the following code :

    #!/bin/bash
    # type "finish" to exit
    
    stty -echoctl # hide ^C
    
    # function called by trap
    other_commands() {
        tput setaf 1
        printf "\rSIGINT caught      "
        tput sgr0
        sleep 1
        printf "\rType a command >>> "
    }
    
    trap 'other_commands' SIGINT
    
    input="$@"
    
    while true; do
        printf "\rType a command >>> "
        read input
        [[ $input == finish ]] && break
        bash -c "$input"
    done
    
    0 讨论(0)
提交回复
热议问题