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


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

Re: Protect Loop Execution with Traps

Started byGreg Wooledge <wooledg@eeg.ccf.org>
First post2020-01-28 08:49 -0500
Last post2020-01-28 08:49 -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

  Re: Protect Loop Execution with Traps Greg Wooledge <wooledg@eeg.ccf.org> - 2020-01-28 08:49 -0500

#15827 — Re: Protect Loop Execution with Traps

FromGreg Wooledge <wooledg@eeg.ccf.org>
Date2020-01-28 08:49 -0500
SubjectRe: Protect Loop Execution with Traps
Message-ID<mailman.244.1580219381.2185.bug-bash@gnu.org>
On Mon, Jan 27, 2020 at 09:03:22PM -0500, Roger wrote:
> I've always had a problem with Bash script (eg. for/while) loops creating havoc 
> upon a ctrl-c keypress.

What's *in* the loop?  It matters.

Consider the following two scripts:

==================================
#!/bin/bash
while true; do
  echo "Zzz"
  sleep 1
done
==================================

==================================
#!/bin/bash
while true; do
  # Assuming Linux
  ping -c 1 8.8.8.8
done
==================================

If you run these, and try to kill them with Ctrl-C, you may find that
the first one behaves perfectly (stops when you ask), and the second
one does not.  It may take several tries to kill the second one.  You
might have better luck suspending it with Ctrl-Z first, then killing
the shell only, then fg'ing the job.

See <https://www.cons.org/cracauer/sigint.html> for details.

In a nutshell, ping(8) is a misbehaving program.  It sets a SIGINT
trap (so that it can report statistics when you interrupt it), but
it doesn't exit as a result of the signal.  The shell sees that the
program didn't exit due to SIGINT, and decides that it (the shell)
should not exit either.

Whatever program you're using inside your loop may have the same
issues.  It's extremely common.

[toc] | [standalone]


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


csiph-web