Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'd like to run chained commands but some are sequential and others are in background.

Running this command:

echo 1 && echo 2 & echo 3 && echo 4

I'd like to get:

1
2 (background)
3
4

But I get:

3
4
1
2

A more realistic example:

compile &&
run server &  (background, used by tests below)
run test 1 &&
run test 2 &&
kill server

How can I do it using bash?

Thanks!

share|improve this question
    
Though not offtopic, I think that this question would be much more at home at unix.stackexchange.com –  Rmano Apr 28 at 20:14
    
I agree. Sorry about that. If an admin / moderator would like to transfer it, go for it. –  David Lojudice Sb. Apr 28 at 22:39

2 Answers 2

up vote 1 down vote accepted

I think that what you are asking for is:

echo 1 && { echo 2 & } && echo 3 && echo 4

In the above echo 1 runs in foreground but echo 2 runs background.

Note that the && after echo 2 may not be doing what you think. Consider:

$ echo 1 && { false & } && echo 3 && echo 4
1
[2] 28445
3
4

The above shows that echo 3 runs even though the second command false returns failure. This is because the return code for the background process is not available when the decision to start echo 3 is made.

Let's consider your more realistic example:

compile && { run server & } && run test 1 && run test 2 && kill server

run test 1 will start regardless of whether run server succeeded or failed. Worse than that, run test 1 may start before run server has finished setting up the server. A quick fix is to delay run test 1 by enough time that you are confident that run server has finished doing its setup:

compile && { run server & } && sleep 1 && run test 1 && run test 2 && kill server

Alternatively, you would need to know something about run server so that you can test its successful setup.

Background

  • The braces, {...}, create a list. Thus the construct { echo 2 & } allows us to run echo 2 with the effect of the operator & confined to just the commands in the list.

  • && is bash's logical and. The command following the && is run only if the prior command succeeds, that is, returns with code 0.

share|improve this answer

You can use nohup to run a command in background : echo 1 && nohup echo 2 && echo 3

1
nohup: ignoring input and appending output to ‘nohup.out’
3
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.