How to Run Multiple Commands in Linux at Once
Running multiple commands in Linux at once can reduce your workload and save you time. It’s a useful technique for those who use the command-line interface (CLI) extensively and want to execute multiple commands at once instead of typing each command separately. In this article, we’ll show you how to run multiple commands in Linux at once.
1. Running Commands in the Background
The simplest way to run multiple commands simultaneously is to use the ampersand symbol “&” to run a command in the background. For example, if you want to run two commands at once, you can use this syntax:
“`
$ command1 & command2 &
“`
This will run both commands in the background, allowing you to continue working in the terminal while the commands execute. You can use as many “&” symbols as you need to run as many commands as you want.
For example, if you want to run three commands simultaneously, you can use this syntax:
“`
$ command1 & command2 & command3 &
“`
2. Running Commands Sequentially
If you want to run multiple commands sequentially, meaning that each command runs after the previous one finishes, you can use the semicolon symbol “;” to separate the commands. For example, if you want to list the content of two different directories, you can use this syntax:
“`
$ ls /directory1; ls /directory2
“`
This will execute the first command, followed by the second command, once the first one is complete.
3. Running Commands in a Script
Another way to run multiple commands simultaneously is to create a script file that contains all the commands you want to run. You can then execute the script file, and all the commands will be executed sequentially.
To create a script file, open a text editor, and type the commands you want to run. For example, if you want to install two packages, you can use this syntax:
“`
#!/bin/bash
sudo apt-get install package1
sudo apt-get install package2
“`
Save the file with any name you like, but make sure to add the “.sh” file extension at the end, like “myscript.sh”. You also need to make the script file executable. To do this, use the chmod command:
“`
$ chmod +x myscript.sh
“`
Now, you can execute the script file by running this command in the terminal:
“`
$ ./myscript.sh
“`
All the commands in the script file will be executed sequentially.
Conclusion
Running multiple commands in Linux at once is a powerful technique that can save you time and effort. Whether you want to run commands in the background, sequentially, or in a script file, Linux provides many options to suit your needs. By mastering this technique, you can become more efficient and productive in your daily work.