2

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It will; try this: date; ( sleep 5; date ) &
I am trying to run this command in loop on different hosts (command1 ; command2) & >/dev/null But it keeps spitting the output on the console and so cannot execute the command second time manually.
I don't think the output would interfere (it depends on your script, I guess), but try this instead: ( command1; command2 ) >/dev/null & You can also do ( command1 >/dev/null; command2 ) & if you only want to suppress output from the first command, for instance.
I noticed both the commands are working one after the other. command1 is creating a file which takes 2 mins and command2 to copying the newly created a file to remote destination. So for the first time the file is not copied remotely as commadn1 is still in process. However second time when I try executing the commands the file gets copied remotely. So that means the first time command1 is still under process and hence file did not get copied remotely.
Is the first command launching itself into the background as well? If it was doing so, then the second command would try to do the move the moment the first command went to the background. Your first command must stay in the foreground until it is complete. It might also be good to have the first command return a proper exit code, the whole command to do what you want would then be: command1 >/dev/null && command2 >/dev/null &
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.