-3

If I have a file with

cmd1

cmd2

cmd3

And I want to run them independent of each other, and independent whether it outputs an exit status or not (that means do not expect to end, just keep starting processes, which can fail or not. I know that ; would run the next command, but that's not the case, because it waits until the previous command either fails or succeeds. I want to start all the commands at once.

It is like something like sleep 60m; and then play music, sound a bell, run the browser, but obviously, there is not way to wait until the music plays to sound a bell, then after that run the browser. It has to happen at once.

ADDED: how to, for example,

read lines from file, open a terminal for each line and run it?

  • 1
    Start those in the background: cmd1 & cmd2 & cmd3 &? – devnull May 5 '14 at 17:55
  • Do these commands expect input or action from the terminal? – Karlson May 5 '14 at 17:55
  • 1
    @devnull Semicolons... – Karlson May 5 '14 at 17:57
  • 3
    @Karlson No, not required. & is a command separator too. Try it if you have any doubts! – devnull May 5 '14 at 17:58
  • @devnull I stand corrected. – Karlson May 5 '14 at 18:00
4

Simply adding an ampersand to the end of each line will fork all the commands into the background.

cmd1 &
cmd2 &
cmd3 &

Example

$ more at_once.bash 
#!/bin/bash

echo "1" && sleep 10 &
echo "2" && sleep 10 &
echo "3" && sleep 10 &
pgrep -a sleep

Now when we run this script:

$ ./at_once.bash 
1
3
2
7533 sleep 10
7535 sleep 10
7536 sleep 10

You can even see that the tasks were run out of order due to their backgrounded nature with the 3rd command being echoed prior to the 2nd one. The pgrep sleep shows that all 3 of the backgrounded commands are running at the same time.

NOTE: I used the notation echo "X" && sleep 10 simply to show that the commands were running backgrounded. This notation has nothing to do with the backgrounding itself, the trailing & is what "puts" the sleep 10 commands into the background.

You can also use & as a separator if you'd rather do this in a single command line:

$ sleep 10 & sleep 10 & sleep 10 &
[1] 7731
[2] 7732
[3] 7733

Checking on this one liner:

$ pgrep -a sleep
7731 sleep 10
7732 sleep 10
7733 sleep 10

Again we see them all running simultaneously. If you were to use a semi-colon:

$ sleep 10 ; sleep 10 ; sleep 10

The sleep 10 commands would run in series taking 30 seconds to complete vs. in parallel, only taking 10 seconds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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