Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

bash - bg / fg inside a command line loop

ctrl-z (^z) acts in ways I do not understand when done inside a loop executed from a terminal.

Say I type

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

then I hit ^z. I'll get:

[1]+  Stopped                 sleep 1

I can resume the job using fg or bg, but the job refers only to he sleep command. The rest of the loop has apparently disappeared, and no more number appear on the terminal.

I could use & after the command to immediately run it in the background, or another solution is to wrap the whole thing 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 job can be resumed and everyone is happy. But I'm not generally in the habit of doing this when running a one-off task, and the question I am asking is why the first behavior happens in the first place. Is there a way to suspend a command-line loop that isn't subshell'd? 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 hitting ^z during the sleep causes the echo 2 to execute:

1
^Z
[2]+  Stopped                 sleep 5
2

Or should I just get in the habit of using & and call it dark magic?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot suspend execution of the current shell. When you run your loop from the command line, it is executing in your current login shell/terminal. When you press [ctrl+z] you are telling the shell to suspend the current active process. Your loop is simply a counter in the current shell, the process being executed is sleep. Suspend only operates on sleep.

When you backgroud a process or execute it in a subshell (roughly equivalent), you can suspend that separate process in total.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...