bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Protect Loop Execution with Traps


From: Roger
Subject: Protect Loop Execution with Traps
Date: Mon, 27 Jan 2020 21:03:22 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

I've always had a problem with Bash script (eg. for/while) loops creating havoc 
upon a ctrl-c keypress.

One good idea, is not to put statements (eg. rm) within the loop that could 
possibly create problems upon partial execution.

Another idea, addressing the monkey within the room, should a trap statement 
always be used within for/while loops?

Or would a trap even help at all?

I've seen some examples on the Internet where a subshell, eg. "( statements )", 
is included within the loop, however this seems to cause more problems as a 
value of a counter variable (i=i+1) cannot be easily incremented due to 
subshells not inherienting previously defined variables of the parent shell.

Example Script: 


#!/bin/bash

declare -i i=0

while (( $i >= 0 )); do
        # Protect loop
        trap "printf 'Caught SIGINT\n'; exit" SIGINT
    
    # Statements here
        printf "Pres CTRL+C to stop... %s\n" ${i}
                
        sleep 1
                
        let "i++"

done




-- 
Roger
http://rogerx.sdf.org/

Attachment: signature.asc
Description: Digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]