0

I want to run 2 commands (command1 and command2) in the same line, where command1 starts a background process and command2 starts a frontground process.

I tried:

command1 & ; command2

But it says: "-bash: syntax error near unexpected token `;'"

How could I run the 2 commands in the same line?

2 Answers 2

2

Try this:

(command1 &); command2

The the syntax (command) is creating a "subshell". You can read here something about it.

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

4 Comments

Why would you want to run the first command in another shell? I don't see the benefit about it in this case.
Oh mainly for clarity. I think it's more readable for a not so expert person.
Mmm yes, I agree it can be read more easily. Only that it is another subshell with all its meanings: variables set in the current shell won't be accessible, etc.
It depends: if you export a variabile in the main shell, you'll see it in the subshell. Anyway, in this simple case, I can't see any variabile problem.
2

; is not helping here. The control operator you need here is & after the first command (thanks Nick Russo in comments):

command1 & command2

From man bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.

Test

$ sleep 10 & echo "yes"
[2] 13368
yes
$ 
[1]-  Done                    sleep 10
$ 

2 Comments

This is the correct answer to the question, though it could be worded even more strongly: The & replaces the ; as the control operator: "Commands separated by a ; are executed sequentially", "If a command is terminated by the control operator &, the shell executes the command in the background in a subshell." linux.die.net/man/1/bash
@NickRusso thanks for the comment, I added it into the answer for better understanding.

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.