1

What is the difference between running following commands on terminal?

command1

for i in {1..3}; do ./script.sh >& log.$i  & done

and

command2

for i in {1..3}; do ./script.sh >& log.$i  & done &

Running the first command shows three job IDs on the screen and I can type the next command on ther terminal.

The second command is a bit weird, it does not show any job IDs on screen nor can I see them after running jobs command. Where did the jobs go?

Inside of script.sh I have following loop

for k in 1; do
 ./tmp -arguments
done

echo "hello"

If I use command 1, I can see via htop that ./tmp executible is running and echo "hello" has not yet been executed (not in the log file).

If I use command 2, I can see via htop that ./tmp executible is running AND echo "hello" has ALREADY been executed (as seen in the log file).

Why would an & on the terminal change the behaviour of the for loop inside the shell script?

[GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)]

2 Answers 2

2

The first one

for i in {1..3}; do
    ./script.sh >& log.$i  &
done

runs in the current shell. Each iteration of the loop runs the script.sh script as a job of the current shell, and so you can see them so.

The second one

for i in {1..3}; do
    ./script.sh >& log.$i  &
done &

first starts a subshell that controls the loop. Then the 3 iterations create 3 subprocesses in that shell, while in your current shell you can only see 1 job, which is the whole command, not yet broken down into particular jobs. (You should see this 1 job. Either as a Running one or as Done.)

The ./tmp executable should run the same way in both cases. If you see echo "hello" has been performed, this means the ./tmp had been finished before. If it behaves abnormally, you should debug (and add the details to your question). Especially, make sure the starting conditions are the same at the time of its call in both cases. Eg. if there are checks for existing files, make sure in both cases they do/don't exist, etc.

-1

The ampersand at the end is causing the command to run in the background. For a complete explanation of this, check out this link.

Running Bash Command in Background

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .