1

This question already has an answer here:

My bash script is supposed to start a process (let's say, run less) and bring it back to foreground every time the process is suspended (e.g. by pressing CTRL-Z).

If I just keep repeating the commands, it works as expected:

#!/bin/bash
set -m
echo foo | less
# (User presses CTRL+Z to suspend the process)
echo "going back..."
sleep 1
fg
# (User presses CTRL+Z to suspend the process)
echo "going back..."
sleep 1
fg
# ... etc.

However, it fails inside a loop:

#!/bin/bash
set -m
echo foo | less
while true; do
    echo "going back..."
    sleep 1
    fg
done

Why does the second script exit the second time I suspend less and not keep looping? Am I missing a side effect of what loops in bash do?

marked as duplicate by muru, Community Apr 12 at 10:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Answer #2: "Bash chooses -- and has always chosen -- to break out of loops when a job is stopped. Continuing the loop is rarely what you want." And like answer #1 suggests, this works correctly in zsh. – muru Apr 12 at 10:01
  • @muru Excellent, thanks for pointing to that. – Arminius Apr 12 at 10:04

Browse other questions tagged or ask your own question.