Thursday, May 16, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 379  / 2 Years ago, sat, january 22, 2022, 8:45:57

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!


More From » command-line

 Answers
6

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.



[#25580] Sunday, January 23, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trousransla

Total Points: 285
Total Questions: 112
Total Answers: 113

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;