Bob van Luijt
Bob van Luijt

Reputation: 7588

How to run a command in bash which captures the output and waits until the command has finished?

I am using the following in a bash script:

command >> /var/log/somelog.log 2>&1&

The reason I'm doing this is because I want to capture all output in /var/log/somelog.log.

This works fine. However it does not wait until the command has finished. So that brings me to the question, how can I capture all output from command in /var/log/somelog.log and not have the bash script continue before command has finished?

Upvotes: 1

Views: 156

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

Just leave out the final ampersand &, e.g.

command >> /var/log/somelog.log 2>&1

From Bash - Lists of Commands

If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true).

Upvotes: 1

Bill Karwin
Bill Karwin

Reputation: 562240

Don't put the command in the background.

The last & character means "run this command in the background, while giving me a new shell prompt immediately."

command >> /var/log/somelog.log 2>&1&
                                    ^ this one

Just take that last character off the command, and the command will run in the foreground until it finishes.

This is frankly pretty introductory stuff. Have you considered reading any documentation about using the shell?

Upvotes: 0

Related Questions