Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #15826

Protect Loop Execution with Traps

From Roger <rogerx.oss@gmail.com>
Newsgroups gnu.bash.bug
Subject Protect Loop Execution with Traps
Date 2020-01-27 21:03 -0500
Message-ID <mailman.243.1580218781.2185.bug-bash@gnu.org> (permalink)
References <20200128020322.GA31704@localhost4.local>

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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/

Back to gnu.bash.bug | Previous | Next | Find similar


Thread

Protect Loop Execution with Traps Roger <rogerx.oss@gmail.com> - 2020-01-27 21:03 -0500

csiph-web