I've been using bash for a long time and ran into something odd today. I'm using GNU bash version 5.2.37(1)-release on Debian testing. I thought I'd share this scenario:
1. I entered the command `while true; do echo hello; sleep 1; done` at the prompt.
2. While the loop was running, I pressed Ctrl-Z to pause it and regain the command prompt.
3. When I typed `fg` to bring it back, I expected the loop to keep printing "hello" indefinitely.
However, it only resumes for one last iteration and then stops. This behavior is confusing to me. Shouldn't an infinite loop continue indefinitely even after a pause? Can someone explain why this happens? Thanks!
3 Answers
Ctrl-Z sends a SIGTSTP signal, which stops the process and might cause some unexpected outcomes with certain commands. It's a good idea to try trapping this signal in bash for your loop. You can use something like `trap 'echo You just pressed Ctrl Z' SIGTSTP`. This might help in dealing with the loop and signal interactions too.
The looping structure definitely requires a condition, but it should ideally keep running unless interrupted. It's curious that the exit status of `sleep` seems to disrupt this. If you replace `true` with something like `:`, that won't change the loop's continuity. I would suggest further testing to see if you can keep it running longer.
It looks like when you hit Ctrl-Z, the 'while' loop gets interrupted by a signal, which affects its ability to restart. You can try modifying your loop a bit by appending `; echo goodbye` to your command like this: `while true; do echo hello; sleep 1; done; echo goodbye`. When you hit Ctrl-Z in this case, you'll get the "goodbye" message. The reason it stops is that the sleep command exits with a non-zero code after the pause. It might be worth experimenting with putting your loop in a subshell to see if that helps.
Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically