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


Groups > gnu.bash.bug > #15826 > unrolled thread

Protect Loop Execution with Traps

Started byRoger <rogerx.oss@gmail.com>
First post2020-01-27 21:03 -0500
Last post2020-01-27 21:03 -0500
Articles 1 — 1 participant

Back to article view | Back to gnu.bash.bug

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#15826 — Protect Loop Execution with Traps

FromRoger <rogerx.oss@gmail.com>
Date2020-01-27 21:03 -0500
SubjectProtect Loop Execution with Traps
Message-ID<mailman.243.1580218781.2185.bug-bash@gnu.org>

[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/

[toc] | [standalone]


Back to top | Article view | gnu.bash.bug


csiph-web