Bg / fg inside the command line loop

ctrl-z (^ z) acts like I donโ€™t understand when executed inside a loop executed from a terminal.

Say I'm typing

for ii in {0..100}; do echo $ii; sleep 1; done 

then i hit ^ z. I will get:

 [1]+ Stopped sleep 1 

I can resume using fg or bg, but the job only applies to the sleep command. The rest of the loop seems to have disappeared and there is no more on the terminal.

I could use and after the command immediately run it in the background or another solution - wrap it all in a subshell:

 ( for ii in {0..100}; do echo $ii; sleep 1; done ) 

then ^ z gives me

 [1]+ Stopped ( for ii in {0..100}; do echo $ii; sleep 1; done ) 

This work can be resumed, and everyone is happy. But I'm usually not used to doing this when doing a one-time task, and the question I ask is why the first behavior occurs in the first place. Is there a way to pause a command line loop that didn't fit? And what happened to the rest of the loop in the first example?

Note that this is specific to the loop:

 echo 1; sleep 5; echo 2 

and pressing ^ z during sleep causes echo 2 execute:

 1 ^Z [2]+ Stopped sleep 5 2 

Or do I just need to get used to using it and call it dark magic?

+6
source share
1 answer

You cannot pause the execution of the current shell . When you start your loop from the command line, it runs in your current shell / login terminal. When you press [ctrl + z], you tell the shell to pause the currently active process. Your loop is just a counter in the current shell, the process is being executed by sleep . Suspend only works during sleep.

When you complete a process or execute it in a subshell (approximately equivalent), you can pause this separate process as a whole.

+5
source

Source: https://habr.com/ru/post/978211/


All Articles