1 min read

Running Multiple Commands in Linux

If you are a Linux user, you may have wondered how to run multiple commands simultaneously, in sequence, in parallel or in other ways. In this post, I will show you some useful tips and tricks to do just that. Let's get started!
Running Multiple Commands in Linux
Photo by Gabriel Heinzer / Unsplash

Running commands in sequence means that one command will run after another, waiting for the previous one to finish. This is the default behaviour of the shell, but you can also use the semicolon (;) operator to separate multiple commands on the same line. For example:

$ echo "Hello" ; echo "World"

This will print "Hello" and "World" on two separate lines.

Running commands in parallel means that multiple commands will run simultaneously without waiting for each other. This can be useful for multitasking or speeding up tasks that don't depend on each other. To run commands in parallel, you can use the ampersand (&) operator to put a command in the background. For example:

$ sleep 10 & echo "Done"

This will start a command that sleeps for 10 seconds in the background and then print "Done" immediately.

You can also use the curly braces ({}) to group multiple commands and run them in parallel. For example:

$ { sleep 5 ; echo "First" ; } & { sleep 10 ; echo "Second" ; }

This will start two groups of commands in the background and print "First" after 5 seconds and "Second" after 10 seconds.

Another way to run commands in parallel is to use the pipe (|) operator to connect one command's output to another's input. This can be useful for processing data or chaining operations. For example:

$ cat file.txt | grep keyword | wc -l

This will count the number of lines in file.txt that contain the word "keyword".

There are other variations of running commands simultaneously, such as using logical operators (&& and ||) to run commands conditionally, using subshells (()) to run commands in a separate environment, or using command substitution ($()) to run commands and use their output as arguments. I encourage you to explore these options and more by reading the man pages or searching online.

I hope you enjoyed this blog post and learned something new. Running multiple Linux commands simultaneously can be a powerful and fun way to use your system.