codec
codec

Reputation: 8806

Executing one shell command after a background command execution

I have 2 commands which I am executing over shell command1 and command2. command1 takes long to complete (~2 minutes). So I can put it running in background using & but after that I want to execute command2 automatically. Can I do this on shell command line?

Upvotes: 2

Views: 3037

Answers (2)

Jeff Breadner
Jeff Breadner

Reputation: 1438

Try:

( command1; command2 ) &

Edit: Larger PoC:

demo.sh:

#!/bin/bash

echo Starting at $(date)
( echo Starting background process at $(date); sleep 5; echo Ending background process at $(date) ) & 
echo Last command in script at $(date)

Running demo.sh:

$ ./demo.sh
Starting at Thu Mar 1 09:11:04 MST 2018
Starting background process at Thu Mar 1 09:11:04 MST 2018
Last command in script at Thu Mar 1 09:11:04 MST 2018
$ Ending background process at Thu Mar 1 09:11:09 MST 2018

Note that the script ended after "Last command in script", but the background process did its "Ending background process" echo 5 seconds later. All of the commands in the (...)& structure are run serially, but are all collectively forked to the background.

Upvotes: 5

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

You can do so by putting both the commends in a shell script and do like below:-

command1 &
wait
command2 & #if you want to run second command also in background

Upvotes: 3

Related Questions