AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / ubuntu / Perguntas / 1431631
Accepted
fixit7
fixit7
Asked: 2022-09-22 14:47:22 +0800 CST2022-09-22 14:47:22 +0800 CST 2022-09-22 14:47:22 +0800 CST

Trap Ctrl+C no script

  • 772

Eu tenho isso do jeito que eu gostaria.

Mas posso descobrir como interceptar Ctrl+ C, para que, se eu quiser encerrar o script antecipadamente, ele possa reativar os modos de suspensão e hibernação.

Eu olhei para outras discussões sobre armadilhas Ctrl+ C, mas não encontrei nenhuma que ajudasse.

Obrigado.

#     TimerInTerminal.sh

# To prevent your Linux system from suspending or going into hibernation, you need to disable the following systemd targets:
# sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target

# To re-enable the suspend and hibernation modes, run the command:
# sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target

soundfile="/usr/share/sounds/My_Sounds/Electronic_Chime.wav"
# Stop computer from sleeping while timer is running

# prevent your Linux system from suspending or going into hibernation
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target

# This allows supend ?
#trap "echo marlin | sudo -S systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target" INT EXIT

if [ $# -eq 1 ]
then
    DURATION="$1"
else
    read -r -p "Timer for how many minutes?( for fractional, use decimal notation , 0.5==30s, 1.25==75s etc) : "  DURATION
    read -r -p "Enter text to display at the end of the timer : " n1
fi

DURATION=$(echo "$DURATION * 60 / 1" | bc) # lets us deal with fractional inputs

START=$(date +%s)   # only do this once (anchor's the time)

countdown () {
    NOW=$(date +%s)              # Get time now in seconds
    DIF=$((NOW - START))         # Compute diff in seconds
    ELAPSE=$((DURATION - DIF))   # Compute elapsed time in seconds
    MINS=$((ELAPSE / 60))        # Convert to minutes... (dumps remainder from division)
    SECS=$((ELAPSE - (MINS*60))) # ... and seconds
    #banner "$MINS:$SECS"
    echo "$MINS:$SECS"
    sleep "$1"
}

while true 
do
    clear
    
    countdown 0 # calc time remaining
    
    if [ $MINS -le 0 ]
    then
        # Blink screen

        while [ $SECS -gt 0 ]
        do
            
            clear # Flash on
            #setterm -term linux -back red -fore white 
            countdown 0.5

            clear # Flash off
            #setterm -term linux -default
            countdown 0.5

        done # End for loop
        
        setterm -term linux -default
        clear
        
        break   # time has expired lets get out of here
    
    else
        countdown 1 
    fi
done

echo $n1
amixer -D pulse sset Master 30% > /dev/null 2>&1
# Play a sound
cvlc --play-and-exit "$soundfile" > /dev/null 2>&1

# To re-enable the suspend and hibernation modes, run the command:
 echo marlin | sudo -S systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target

Isso funciona. Não vou inserir meu código inteiro em ctrl_c e ver o que acontece.

 #!/bin/bash
    # trap ctrl-c and call ctrl_c()
    trap ctrl_c INT
    
    function ctrl_c() {
            echo "** Trapped CTRL-C"
    echo System will now have suspension/hibernation halted.
    
    # prevent your Linux system from suspending or going into hibernation
    sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
    sleep 10
}
ctrl_c
bash
  • 1 1 respostas
  • 117 Views

1 respostas

  • Voted
  1. Best Answer
    Terrance
    2022-09-23T16:44:42+08:002022-09-23T16:44:42+08:00

    Aqui está como você pode capturar o CTRL+Cno script. Você não chama a ctrl_cfunção, pois ela será chamada quando você pressionar CTRL+ Cno teclado. Eu adicionei um exit 0para que ele saia do script depois que ele intercepte CTRL+Ce pare de fazer o loop pelo arquivo for .. loop.

    cat ctrl_test.bsh 
    #!/bin/bash
    
    #Setup trap command, assign what to call and what is the trigger (SIGINT)
    trap ctrl_c INT
    
    #Function of what trap command calls    
    function ctrl_c() {
        printf "\n** Trapped CTRL-C after $i seconds.\n"
        exit 0
    }
    
    #Rest of script to print counting numbers to screen will not break with CTRL+C due to trap
    for ((i=1;i>0;i++))
    do
        printf "\r$i"
        sleep 1
    done
    

    Exemplo:

    terrance@terrance-ubuntu:~$ ./ctrl_test.bsh 
    13^C
    ** Trapped CTRL-C after 13 seconds.
    terrance@terrance-ubuntu:~$ 
    

    No seu caso de script, você poderia fazer algo assim:

    #TimerInTerminal.sh
    
    #Trap Ctrl+C and re-enable suspend and hibernation modes
    trap ctrl_c INT
    function ctrl_c() {
        sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target
        exit 0
    }
    
    # To prevent your Linux system from suspending or going into hibernation, you need to disable the following systemd targets:
    # sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
    
    # To re-enable the suspend and hibernation modes, run the command:
    # sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target
    
    soundfile="/usr/share/sounds/My_Sounds/Electronic_Chime.wav"
    # Stop computer from sleeping while timer is running
    
    # prevent your Linux system from suspending or going into hibernation
    sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
    
    # This allows supend ?
    #trap "echo marlin | sudo -S systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target" INT EXIT
    
    if [ $# -eq 1 ]
    then
        DURATION="$1"
    else
        read -r -p "Timer for how many minutes?( for fractional, use decimal notation , 0.5==30s, 1.25==75s etc) : "  DURATION
        read -r -p "Enter text to display at the end of the timer : " n1
    fi
    
    DURATION=$(echo "$DURATION * 60 / 1" | bc) # lets us deal with fractional inputs
    
    START=$(date +%s)   # only do this once (anchor's the time)
    
    countdown () {
        NOW=$(date +%s)              # Get time now in seconds
        DIF=$((NOW - START))         # Compute diff in seconds
        ELAPSE=$((DURATION - DIF))   # Compute elapsed time in seconds
        MINS=$((ELAPSE / 60))        # Convert to minutes... (dumps remainder from division)
        SECS=$((ELAPSE - (MINS*60))) # ... and seconds
        #banner "$MINS:$SECS"
        echo "$MINS:$SECS"
        sleep "$1"
    }
    
    while true 
    do
        clear
        
        countdown 0 # calc time remaining
        
        if [ $MINS -le 0 ]
        then
            # Blink screen
    
            while [ $SECS -gt 0 ]
            do
                
                clear # Flash on
                #setterm -term linux -back red -fore white 
                countdown 0.5
    
                clear # Flash off
                #setterm -term linux -default
                countdown 0.5
    
            done # End for loop
            
            setterm -term linux -default
            clear
            
            break   # time has expired lets get out of here
        
        else
            countdown 1 
        fi
    done
    
    echo $n1
    amixer -D pulse sset Master 30% > /dev/null 2>&1
    # Play a sound
    cvlc --play-and-exit "$soundfile" > /dev/null 2>&1
    
    # To re-enable the suspend and hibernation modes, run the command:
     echo marlin | sudo -S systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target
    
    • 2

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Existe um comando para listar todos os usuários? Também para adicionar, excluir, modificar usuários, no terminal?

    • 9 respostas
  • Marko Smith

    Como excluir um diretório não vazio no Terminal?

    • 4 respostas
  • Marko Smith

    Como descompactar um arquivo zip do Terminal?

    • 9 respostas
  • Marko Smith

    Como instalo um arquivo .deb por meio da linha de comando?

    • 11 respostas
  • Marko Smith

    Como instalo um arquivo .tar.gz (ou .tar.bz2)?

    • 14 respostas
  • Marko Smith

    Como listar todos os pacotes instalados

    • 24 respostas
  • Martin Hope
    Flimm Como posso usar o docker sem sudo? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    led-Zepp Como faço para salvar a saída do terminal em um arquivo? 2014-02-15 11:49:07 +0800 CST
  • Martin Hope
    ubuntu-nerd Como descompactar um arquivo zip do Terminal? 2011-12-11 20:37:54 +0800 CST
  • Martin Hope
    TheXed Como instalo um arquivo .deb por meio da linha de comando? 2011-05-07 09:40:28 +0800 CST
  • Martin Hope
    Ivan Como listar todos os pacotes instalados 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    David Barry Como determino o tamanho total de um diretório (pasta) na linha de comando? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher "Os seguintes pacotes foram retidos:" Por que e como resolvo isso? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford Como os PPAs podem ser removidos? 2010-07-30 01:09:42 +0800 CST

Hot tag

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve