Categories
Device

How to run two or more terminal commands at once in linux

Lori Kaufman is a technology expert with 25 years of experience. She’s been a senior technical writer, worked as a programmer, and has even run her own multi-location business. Read more.

How to run two or more terminal commands at once in linux

If you use Linux, you know how useful the command line can be for working with files, installing software, and launching programs. But it can be even more efficient if you run multiple commands at once.

Combining two or more commands on the command line is also known as “command chaining”. We’ll show you different ways you can combine commands on the command line.

Option One: The Semicolon (;) Operator

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint). Then, type the following three commands on one line, separated by semicolons, and press Enter. This will give you a listing of the current directory ( ls ), find out which directory you’re currently in ( pwd ), and display your login name ( whoami ) all at once.

You don’t have to put spaces between the semicolons and the commands, either. You can enter the three commands as ls;pwd;whoami . However, spaces make the combined command more readable, which is especially useful if you’re putting a combined command into a shell script.

How to run two or more terminal commands at once in linux

Option Two: The Logical AND Operator (&&)

If you want the second command to only run if the first command is successful, separate the commands with the logical AND operator, which is two ampersands ( && ). For example, we want to make a directory called MyFolder and then change to that directory–provided it was successfully created. So, we type the following on the command line and press Enter.

The folder was successfully created, so the cd command was executed and we are now in the new folder.

We recommend using the logical AND operator rather than the semicolon operator most of the time ( ; ). This ensures that you don’t do anything disastrous. For example, if you run a command to change to a directory and then force remove everything in that directory recursively ( cd /some_directory ; rm -Rf * ), you could end up ruining your system if the directory change didn’t happen. Not that we recommend you run a command to unconditionally remove all files in a directory at once.

How to run two or more terminal commands at once in linux

Option Three: The Logical OR Operator (||)

Sometimes you might want to execute a second command only if the first command does not succeed. To do this, we use the logical OR operator, or two vertical bars ( || ). For example, we want to check to see if the MyFolder directory exists ( [ -d

/MyFolder ] ) and create it if it doesn’t ( mkdir

/MyFolder ). So, we type the following command at the prompt and press Enter.

Be sure there is a space after the first bracket and before the second bracket or the first command that checks if the directory exists will not work.

In our example, the MyFolder directory does not exist, so the second command creates the directory.

How to run two or more terminal commands at once in linux

Combining Multiple Operators

You can combine multiple operators on the command line, too. For example, we want to first check if a file exists ( [ -f

/sample.txt ] ). If it does, we print a message to the screen saying so ( echo “File exists.” ). If not, we create the file ( touch

/sample.txt ). So, we type the following at the command prompt and press Enter.

In our example, the file didn’t exist, so it was created.

How to run two or more terminal commands at once in linux

Here’s a useful summary of each of the operators used to combine commands:

  • A ; B — Run A and then B, regardless of the success or failure of A
  • A && B — Run B only if A succeeded
  • A || B — Run B only if A failed

All of these methods of combining commands can also be used in shell scripts on both Linux and Windows 10.

Last updated September 15, 2020 By Abhishek Prakash 35 Comments

Running two or more commands in one line can save you a good deal of time and help you become more efficient and productive in Linux.

There are three ways you can run multiple commands in one line in Linux:

; Command 1 ; Command 2 Run command 1 first and then command 2
&& Command 1 && Command 2 Run command 2 only if command 1 ends sucessfully
|| Command 1 || Command 2 Run command 2 only if command 1 fails

Let me show you in detail how you can chain commands in Linux.

How to run two or more terminal commands at once in linux

Using ; to run multiple Linux commands in one line

The simplest of them all is the semicolon (;). You just combine several commands that you want to run using ; in the following fashion:

Here, cmd1 will run first. Irrespective of whether cmd1 runs successfully or with error, cmd2 will run after it. And when cmd2 command finishes, cmd3 will run.

Let’s take an example you can practice easily (if you want to).

In the above command, you first create a new directory named new_dir with mkdir command. Then you switch to this newly created directory using cd command. Lastly you print your current location with pwd command.

” data-medium-file=”https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux-300×110.png” data-large-file=”https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux.png” loading=”lazy” width=”755″ height=”277″ src=”https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux.png” alt=”Running Multiple Commands Linux” data-lazy-srcset=”https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux.png 755w, https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux-300×110.png 300w” data-lazy-sizes=”(max-width: 755px) 100vw, 755px” data-lazy-src=”https://itsfoss.com/wp-content/uploads/2020/09/running-multiple-commands-linux.png?is-pending-load=1″ srcset=”data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″> Running Multiple Commands Linux with ;

The space after semicolon (;) is optional but it makes the chain of commands easily readable.

Using && to run multiple Linux commands

Some times you want to ensure that the in the chain of Linux commands, the next command only runs when the previous command ends successfully. This is where the logical AND operator && comes into picture:

If you use Ubuntu or Debian based distributions, you must have come across this command that utilizes && concept:

Here the first command (sudo apt update) first refreshes the package database cache. If there is no error, it will then upgrade all the packages that have newer versions available.

Let’s take earlier example. If the new_dir already exists, mkdir command will return error. The difference in the behavior of ; and && can be see in the screenshot below:

” data-medium-file=”https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line-300×108.png” data-large-file=”https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line.png” loading=”lazy” width=”768″ height=”277″ src=”https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line.png” alt=”Multiple Linux Commands One Line” data-lazy-srcset=”https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line.png 768w, https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line-300×108.png 300w” data-lazy-sizes=”(max-width: 768px) 100vw, 768px” data-lazy-src=”https://itsfoss.com/wp-content/uploads/2020/09/multiple-linux-commands-one-line.png?is-pending-load=1″ srcset=”data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″>

Did you see how commands separated by && stopped when the first command resulted into error?

Using || to run several Linux commands at once

You can use the logical OR operator (||) to run a chain of commands but the next command only runs when the previous command ends in error. This is opposite to what you saw with &&.

If cmd1 fails, cmd2 runs. If cmd2 runs successfully, cmd3 won’t run.

How to run two or more terminal commands at once in linux

In the screenshot above, mkdir new_dir command fails because new_dir already exists. Since this command fails, the next command cd new_dir is executed successfully. And now that this command has run successfully, the next command pwd won’t run.

Bonus Tip: Combine && and || operators

You may combine the operators to run two or more Linux commands.

For example, you can check if file exists in bash, and print messages accordingly.

Run the above command before and after creating the file.txt file to see the difference:

” data-medium-file=”https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-300×113.png” data-large-file=”https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-800×300.png” loading=”lazy” width=”800″ height=”300″ src=”https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-800×300.png” alt=”Combine Multiple Commands Linux” data-lazy-srcset=”https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-800×300.png 800w, https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-300×113.png 300w, https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-768×288.png 768w, https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux.png 807w” data-lazy-sizes=”(max-width: 800px) 100vw, 800px” data-lazy-src=”https://itsfoss.com/wp-content/uploads/2020/09/combine-multiple-commands-linux-800×300.png?is-pending-load=1″ srcset=”data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″>

Like copy-paste in Linux terminal, running multiple commands at once is also one of the many Linux command line tips for saving time. Though elementary, it is an essential concept any Linux terminal user should know.

You can also use ;, && and || to run multiple commands in bash scripts as well.

I hope you liked this terminal trick. Stay tuned for more Linux command tips and tools published every Tuesday under the #TerminalTuesday series.

Like what you read? Please share it with others.

Running two or more commands on one line can save you a lot of time and help you be more efficient and productive on Linux.

There are three ways to run multiple commands on one line in Linux:

; Command 1; Command 2 Run command 1 first and then command 2
&& Command 1 && Command 2 Run command 2 only if command 1 completes successfully
|| Command 1 || Command 2 Run command 2 only if command 1 fails

Let me show you in detail how you can chain commands in Linux.

Using ; to run multiple linux commands on one line

The simplest of them all is the semicolon (;). Just combine multiple commands you want to run using ; as follows:

Here, cmd1 will be executed first. Regardless of whether cmd1 runs successfully or fails, cmd2 will run afterward. And when the cmd2 command is finished, cmd3 will be executed.

let’s take an example you can easily practice (if you want).

In the above command, you first create a new directory called new_dir with the mkdir command. Then change to this newly created directory using the cd command. Lastly, print your current location with the pwd command.

Execute multiple Linux commands with ;

The space after the semicolon (;) is optional but makes the command string easily readable.

Using && to run various Linux commands

Sometimes you want to make sure that in the Linux command string, the the following command is only executed when the previous command completes successfully. This is where the logical AND && operator comes into the picture:

If you use distributions based on Ubuntu o Debian, you must have found this command which uses the && concept:

Here the first command (sudo apt update) first updates the package database cache. If there are no errors, it will update all packages that have newer versions available.

Let’s take example first. If new_dir already exists, the mkdir command will return an error. The difference in the behavior of ; and && can be seen in the following screenshot:

Did you see how commands separated by && stopped when the first command resulted in an error?

Using || to run multiple Linux commands at once

You can use the logical OR operator (||) to execute a chain of commands, but the the following command is only executed when the previous command ends with an error. This is opposite of what you saw with &&.

If cmd1 fails, cmd2 is executed. If cmd2 runs successfully, cmd3 will not run.

In the screenshot above, the mkdir new_dir command fails because new_dir already exists. Since this command fails, the following cd new_dir command succeeds. And now that this command has been executed successfully, the next pwd command will not be executed.

Bonus Tip: Combine && and || operators

You can combine the operators to run two or more Linux commands.

For example you can check if file exists in bashand print messages accordingly.

Run the above command before and after creating the file.txt file to see the difference:

Just like copying and pasting in the Linux terminal, running multiple commands at once is also one of the many time-saving Linux command line tips. Although elementary, it is an essential concept that any Linux terminal user should know.

You can also use ;, && and || to execute various commands in bash scripts as well.

I hope you liked this terminal hack. Stay tuned for more Linux command tips and tools posted every Tuesday in the #TerminalTuesday series.

The Linux Terminal is a powerful tool that allows you to perform a wide variety of operations using commands. You can use these commands to perform a wide variety of computing tasks, including file manipulation, program management, and service automation.

If you need to run a series of terminal commands, ideally do them one at a time. It turns out, however, that there is a better way to do this, and it involves executing multiple commands at the same time.

Follow us as we demonstrate the different ways you can run multiple terminal commands on Linux.

Execute multiple Linux commands at the same time

On Linux there are three ways to run multiple commands in a terminal:

  1. the semicolon (;) Operator
  2. the Logical OR (||) Operator
  3. the Logical AND (&&) Operator

All of these methods require an operator. Although any of these operators can execute two or more shell commands at the same time, knowing which operator to use and when can help you create effective commands. The following sections explain both the purpose and syntax for using these operators properly.

1. Using the semicolon (;) operator

Segmenting a chain of commands with the semicolon is the most common practice when you want to execute multiple commands in a terminal. One reason for this is the way the operator works: it executes all commands in order, regardless of whether the previous command ran successfully or failed.

For example, if there are two commands: Command A and Command B, the semicolon operator in between ensures that both the first and second commands are executed sequentially, regardless of the output of the first command.

So, if you’re in a situation where two or more independent terminal commands need to be executed so that the output status of the first command doesn’t affect the execution of the latter, the semicolon operator is the way to go.

Example use case: To display the current user name and the system host name:

Note, however, that the shell executes these commands in the order in which you mention them. This is what the output would look like:

2. Using the OR operator (||)

The definition of the word “or” here is just one character: When you run two commands with the OR operator, you are telling the shell to run only one command between the two.

Imagine a scenario where you used the OR operator with two commands: Command A and Command B. This is what the linked command would look like with the OR operator:

Here, Command B will only run if Command A fails, ie if Command A returns an error. Likewise if Command A runs successfully, Command B will not be performed.

Speaking of the use case, you can use the OR operator when you need to run two related commands together so that the shell only runs the next command if the previous one fails.

Example use case: Let’s say you want to create a new file, let’s say Document.txt, but before doing this you want to make sure that there is no file with the same name in the current directory. In situations like this, you can run your commands in the following order:

Here the find command looks for the in the current working directory Documents.txt File. If the file is found, the command history will stop – and the second command will not run.

On the other hand, if it doesn’t find a suitable file, the command on the right is executed and a new file named Document.txt is created in your current working directory.

3.Using the AND operator (&&)

As you have probably guessed by now, the AND operator will only execute the next instruction in a sequence if the previous instruction was successful.

To understand this better, imagine a scenario where you want to run two related commands so that you only want the second command to run if the first returns valid output. In this case we can join the commands together using the AND operator called && to get the result we want.

Example use case: One of the most common use cases of the AND operator in Linux is to create a new directory and access it immediately. That way, you don’t have to run the two commands individually to complete the operation.

For this tutorial, let’s say you want a new directory called. create documents and immediately change your current working directory there.

Here that mkdir Command creates a new directory called documents in your current working directory. If this is successful, the cd command can be executed.

Combine multiple operators to meet your execution criteria

In addition to using operators individually in your commands, you can also group multiple operators to meet your execution criteria. This is useful when you want to run commands based on multiple conditions.

Imagine a scenario where you want to run two commands (Command B and Command C) only if Command A fails. To do this, you need to use operators as shown in the following notation:

Example use case: Suppose you want to determine if a folder (named Document) exists in your current working directory and create it if it isn’t there. In that case, instead of running separate commands to find the directory and create a new one, you can use the OR and AND operators together to do the whole process efficiently.

This is what it would look like:

In this command Find asks the shell for a folder named. to search Document in the current working directory. If the directory does not exist, the terminal transfers the flow to the echo and mkdir Commands that print the specified string or create a new folder.

Efficient execution of terminal commands on Linux

As you just saw, using operators in your commands can simplify many command line operations.

If you are someone who enjoys doing various system operations on your computer through the terminal, knowing how to use these operators can be very helpful and will definitely help you execute Linux commands more efficiently.

If you are just starting out with Linux or are less familiar, learning various terminal commands is another step in mastering the command line interface.

If you use Linux daily, you will know that the command line is the most powerful tool when you working with files, installing and configuring system software, and running them. It becomes even more efficient if you run two or more commands at once on the command line and save a good deal of time.

In this tutorial, we’ll see the different ways in which we can combine and execute multiple Linux commands efficiently in one single line.

; cmd1; cmd2 The “;” operator runs all commands regardless of whether the earlier ones are failed or not.
&& cmd1 && cmd2 The “&&” operator carries out the second command only if the preceding command executes successfully.
|| cmd1 || cmd2 The “||” operator executes the second command only if the precedent command returns an error.

Let me explain to you in more detail how you can execute multiple commands in Linux in one go.

1. Using Semicolon (;) Operator to Run Multiple Linux commands

The semicolon (;) operator enables you to run one or more commands in succession, regardless of whether each earlier command succeeds or not. For example, run the following three commands on one line separated by semicolons (;) and hit enter.

How to run two or more terminal commands at once in linuxRun Multiple Commands Using Semicolon Operator

This will show you a listing of the current directory ( ls ), show which directory you’re currently in ( pwd ), print the disk usage of files (du), and display your account login name ( whoami ) all at once.

2. Using AND (&&) Operator to Run Multiple Linux Commands

In some scenarios, you want to make sure that the second command only executes if the first command is executed successfully. For example, run the two commands separated by (&&) operator, which is two ampersands.

Here the first command updates the package database lists for packages that need upgrading. If there are no errors, it will execute the second command that will upgrade all the packages to a newer version.

I highly recommend using the (&&) operator rather than using (;) semicolon operator most of the time. This assures that you don’t do anything terrible. For example, if you run the following command to change to a directory and then delete everything recursively in that directory, you could end up destroying your system if the directory change didn’t take place.

3. Using (||) Operator to Run Several Linux Commands

At times you might want to run a second command only if the first command returns an error. To do this, you need to use (||) operator. For example, you want to verify that if the MyFolder directory exists and create it if it doesn’t.

In the above example, the MyFolder directory does not exist, so the second command creates the directory.

Conclusion

In this article, we have learned the three useful ways in which we can combine and run multiple Linux commands in the command line productively.

Is there any way how I can run two Db2 commands from a command line? They will be called from a PHP exec command.

  1. db2 connect to ttt (note that we need to have the connection live for the second command
  2. db2 UPDATE CONTACT SET EMAIL_ADDRESS = ‘[email protected]

The first command finishes correctly, but the second one fails with the following error message:

SQL1024N A database connection does not exist. SQLSTATE=08003

Note that I need to run this as php user. The command sudo -u db2inst1 id as php user gives me correct output.

How to run two or more terminal commands at once in linux

10 Answers 10

For your command you also could refer to the following example:

sudo sh -c ‘whoami; whoami’

sudo can run multiple commands via a shell, for example:

Your command would be something like:

If your sudo version doesn’t work with semicolons with -s (apparently, it doesn’t if compiled with certain options), you can use

instead, which basically does the same thing but makes you name the shell explicitly.

How to run two or more terminal commands at once in linux

If you would like to handle quotes:

An alternative using eval so avoiding use of a subshell:

Note: The other answers using sudo -s fail because the quotes are being passed on to bash and run as a single command so need to strip quotes with eval. eval is better explained is this SO answer

Quoting within the commands is easier too:

And if the commands need to stop running if one fails use double-ampersands instead of semi-colons:

The -s option didn’t work for me, -i did.

Here is an example of how I could update the log size from my bash:

On the terminal, type:

Then write as many commands as you want. Type exit when you done.

If you need to automate it, create a script.sh file and run it:

How to run two or more terminal commands at once in linux

On a slightly-related topic, I wanted to do the same multi-command sudo via SSH but none of the above worked.

For example on Ubuntu,

The trick discovered here is to double-quote the command.

Other options that also work:

In principle, double-quotes are needed because I think the client shell where SSH is run strips the outermost set of quotes. Mix and match the quotes to your needs (eg. variables need to be passed in). However YMMV with the quotes especially if the remote commands are complex. In that case, a tool like Ansible will make a better choice.

You may know the how to use & to run commands in the background, but it also has this other very interesting use case.

We can run two or more commands asynchronously using the single ampersand & character.

Asynchronous Commands

Suppose we had three scripts we wanted to run simultaneously.

All three Python scripts will run simultaneously in separate sub-shells, allowing you to take advantage of multiple cores. The output of all three, however, will all be attached to this parent shell. This means each line will be displayed on a first-come, first-serve basis.

If you’re having trouble running Python scripts through bash like this, you may have forgotten to add #!/usr/bin/env python to the top of your script. Another alternative is just to run the scripts through the python command python s1.py .

If you need to examine the output of each separately, it may be helpful to redirect each script output to a file.

Because this is asynchronous, none of these commands should depend on one another.

For example, this string of commands would cause issues.

In the second command, we are looking for the text some_text in the output of the first command, which doesn’t exist yet.

This is why we may need synchronous commands.

We can run two or more commands synchronously using double ampersands && .

Synchronous Commands

One thing to note with && is that each subsequent command is dependent on the success of the previous command.

If command1 fails, command2 will never run. If command2 fails, command3 will never run, and so on .

Continuing with our previous example:

This is a valid command using && .

grep “some_text” out1.txt will run as long as ./s1.py doesn’t contain any errors.

The Situation

In the world of computing being able to execute multiple commands at the same time is a big deal. Even early operating system were able to execute multiple commands at once. Now days multiple execute is corner stone to everything from virtualization hardware to operating systems to games and audio / video processing. In fact, I beat you have more than one browser tab open right now, and probably running more than one program as well. Multi-core processors increase parallel command execution even further!

Why, then, is it not easier to run multiple commands in parallel in user space? Maybe I want to download 3 files at the same time? Maybe I want to perf. compare three scripts at the same time. Or any number of uses of parallel execution. I am not talking about running a program in the background with command 1 & nor series execution with && . True same-time process execution

The Solution

One of the best Linux tools to run commands in parallel is, maybe not surprisingly, called parallel. Go figure, a tool named after what it does :S. It is available via most Linux distributions package manager. The –help is helpful and the man parellel is in depth. Some of it can seem daunting but remember, no one knows everything. Just learn what you can

An Example

Before trying out the new fancy tool lets get a base line. I created a script downloads a 5MB file three times, in a loop of three. So 9 downloads of 5MB is about 45MB (./lib/test_0.sh). Here is the result of three runs.

Now, we run the same wget command against the same three targets, but this time via parallel (test_1.sh). Once again lets do it three times to get an average.

Is this a synthetic test limited by my bandwidth? Sure, but even in this small example it saved approx. 30% per script execution. Imagine larger, longer running processes; or even more processes. With parallel each iteration only takes as long as the longest response.

In Conclusion

Think of parallel as an async tool for Linux CLI. Where you were once limited to running commands in series you can now execute in parallel. Want to move an entire directory of files as fast as the disk can handle? Iterate the file list and mv via parallel. Want to download 5 files at the same time? parallel it. Want to run all your clean up scripts at the same time? parallel them.

Soon(tm)

This article was just an introduction to the parallel tool. In the next article in this series I will show how to use the parallel tool in a automated pipeline to decrease test execution time. Stay tuned for that one.

I need to run several Bash scripts (the same script with different variables to be precise) at the same time. To keep the number of tabs under control, I wish to group them in a single terminal tab.

The scripts regularly output, which I check for any problem.

If I send them to the background as

I will lose control over them. For example, I terminate the script by Ctrl + C . With the above code, I should find the pid for each process to kill them.

Note that the above code is the content of my main script (say ./all_scripts.sh ) rather than commands to be typed in the terminal.

Is there a way to run the script in the same terminal while treating them as a single outputting script?

8 Answers 8

You don’t lose control over them. You’re sending them (other than the last one) to the background.

If you run the command chain you specify, the invocation ./script.sh 4 will be in the foreground, and the other scripts will be running in the background. Input will be sent to the foreground script. To suspend the foreground script, press Ctrl Z . To send the suspended script to the background to continue running, use the bg command.

To see the scripts (or more correctly, jobs) you have and the states they’re in, use jobs .

To bring a specific job to the fore, use fg and its number (as reported by the aforementioned jobs ) with a % prefix, e. g. fg %2 . To terminate a specific job, you can either bring it to the foreground with fg and terminate it sanely, or you can kill it, e. g. kill -TERM %2 .

After testing different methods and programs, I found that the pragmatic solution is GNU Parallel. I post this answer as it may help others.

GNU Parallel has not been built for this task, but perfectly serves the purpose.

If running the scripts as

All scripts will be run in parallel.

The -u ( –ungroup ) flag sends the script outputs into stdout while executing the scripts.

Ctrl + C kills the parallel job, and subsequently all running scripts.

You can redirect the output to a file (one per process or a combined one). Having one file for all is not a problem if the writes are small (512 byte is safe, probably even 4K). Small writes are atomic:

If you are doing that interactively then the following may help: You can easily address the jobs by prepending a (otherwise useless) environment variable definition (like BackGround Task ID):

The command prefix just must be unambigeous (so no bgtid=foo and bgtid=foobar ).

How to run two or more terminal commands at once in linux

You can use tmux for this.

It is a terminal multiplexer meaning that it splits one tab into multiple windows.

  • Start it with the command tmux .
  • Use Contr +B followed by ” or % in order to split a pane into two panes.
  • Start processes in the foreground.
  • Switch between the processes uding Contr + B followed by arrow keys.

Now you have normal control over multiple processes in one tab of your terminal.

If you want to focus (or unfocus) a specific pane, use Contr + B followed by Z .

If you need to scroll use Contr + B followed by Q and scroll using arrow keys(or activate mouse mode).

You can find a cheatsheet here.

It is also possible to automate that process.

How to run two or more terminal commands at once in linux

You can find this tool with the ‘tsp’ alias in debian and ubuntu .

How to run two or more terminal commands at once in linux

echo -e “1\n2\n3\n4\n” | xargs -n1 -P4 ./script.sh

Is another way of doing this. xargs is available on basically any system, and control-c should kill all the jobs.

It also (unlike invoking your scripts with & , allows you to run this from a higher-level bash script)

The -n1 option tells xargs to run each argument in it’s own process, and the -P4 option tells it to run 4 processes.

I would like to mention an interesting feature of tmux (tmux has already been given as an excellent option by @dan1st). There is a way to run the same command simultaneously in multiple panes. Here is an example. I want to run echo “Fruit name is $fruit” on two different panes/logins/hosts at the same time. Steps:

  1. Launch tmux: tmux new-session -s myparallel
  2. CTRL-B followed by ” (this will split the pane into two. If you want more panes, repeat. ” splits horizontally, % splits vertically)
  3. Navigate to each pane (using CTRL-B and arrow key) to set the variable for that pane. For example, pane #1 will have fruit=”apple” while pane #2 will have fruit=”orange”
  4. Now that you have the variables set on a pane basis, it is time to synchronize the panes so that whatever you type in one will be mirrored across all panes. The command to do this is CTRL-B :setw synchronize-panes on
  5. Now you can run scriptName $fruit and view the output on all panes at the same time.
  6. For the sake of completeness, to exit the synchronized mode, type CTRL-B :setw synchronize-panes off

When backgrounding jobs, the shell variable that is printed using: “echo $!” gives the process ID number of the last backgrounded job. You can create a shell script array that holds these process numbers, as you background, and can deal with the processes as you need them. (i.e. you can check to see if they are still running with “ps” or you can kill them.)

Just checked, in bash, the “echo $!” or “shellvar=$!” needs to be on a new line, since “;” does not work after “&”.

If you are managing multiple Linux servers, and you want to run multiple commands on all the Linux servers, but you have no idea about how to do it. There is no need to worry, in this simple server management guide, we will show you how to run multiple commands on multiple Linux servers simultaneously.

To achieve, this you can use the pssh (parallel ssh) program, a command line utility for executing ssh in parallel on a number of hosts. With it, you can send input to all of the ssh processes, from a shell script.

Requirements

  1. Install Pssh to Run Commands on Multiple Remote Linux Servers
  2. You must be using SSH passwordless authentication for all remote servers.

Create a Shell Script

Therefore, you need to start by preparing a script which contains the Linux commands you want to execute on the different servers. In this example, we will write a script that will collect the following information from multiple servers:

  • Check uptime of servers
  • Check who is logged on and what they are doing
  • List top 5 running processes according to memory usage.

First create a script called commands.sh with your favorite editor.

Next, add the following commands to the script as shown.

Save the file and close it. Then make the script executable as shown.

Create PSSH Hosts File

Next, add the list of servers that you want to run the commands on, in a hosts.txt file, in the format [[email protected]]host[:port] or simply give the server IP addresses.

But we suggest you use ssh aliases which can be specified in .ssh/config file as explained in how to configure custom ssh connections to simplify remote access.

This method is more efficient and reliable, it allows you to specify configuration options (such as host name, identify file, port, username etc..) for each remote server.

Following is our sample ssh hosts aliases file a.k.a user specific ssh configuration file.

SSH Hosts Aliases File

Next, create a hosts.txt file, here you can simply specify the aliases (names defined using Host keyword in .ssh/config file) as shown.

Add the server aliases.

Run Commands via a Script on Multiple Linux Servers

Now run the following pssh command by specifying hosts.txt file along with the script that contains multiple commands to run on multiple remote servers.

Meaning of the flags used in the above command:

  • -h – reads the hosts file.
  • -P – tells pssh to display output as it arrives.
  • -I – reads input and sends to each ssh process.

Run Multiple Commands On Remote Servers

That’s It! In this article, we showed how to execute multiple commands on multiple servers in Linux. You can share any thoughts relating to this topic via the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Different types of commands are needed to run from the terminal in Linux. Sometimes we need to run multiple commands at a time where the commands can depend on each other or not. Running multiple commands at once is called command chaining. Many types of operators can be used for command chaining for different purposes. How you can run two or more commands by using most commonly used operators is shown in this tutorial.

pipe(|) operator is used to run two or more related commands at a time. The input of the next command will be the output of the previous command. So, the success of each command depends on the success of earlier command without first command. In the following command, the first command, ls will find out the list of files and folders of the current location and send the output as input for the second command, wc. It will print the total number of lines, words, and characters based on the input data.

Semicolon (;) Operator

Semicolon(;) operator is used to running two or more unrelated commands at a time. This means that the output of each command is not dependent on other commands. In the following example, three types of commands are combined together and the failure of each command will not create an effect on the output of other commands. The first command will print the content of a file, the second command will make a directory and the third command will change the current directory.

$ cat myfile.txt ; mkdir newdir ; cd Desktop

Logical AND (&&) operator

The commands which run by Logical AND (&&) are related with each other like pipe (|) command. So, if the previous command will not execute successfully then the next commands will not work. In the following example, two commands, mkdir, and rmdir combined by && operators. So, it mkdir command is failed to execute successfully then rmdir command will not execute. According to the output of ls command, myDir directory already exists in the current location. So the first command will not execute and for this second command will not execute also.

$ ls
$ mkdir myDir && rmdir temp
$ ls

Logical OR (||) operator

Logical OR (||) operator is the opposite of the Logical AND (&&) operator. The next command will execute if the previous command fails to execute. Three cat commands are combined with OR (||) operator in the following example. When you will run the command, first of all, it will try to display the content of cat.txt file. If no such file exists in the current location then it will try to execute the next command. According to the output, bird.txt file exists in the current location and the content of this file is displayed.

$ cat cat.txt || cat dog.txt || cat bird.txt

Multiple commands with multiple operators

You can use multiple operators to run multiple commands at a time. In the following example, three commands are combined with OR (||) and AND (&&) operators. After running the command, first of all, it will change the current directory to newdir if the directory exists. If this command fails then it will create the directory by executing the second command and print the message, “directory is created.” According to the output, newdir directory not exist in the current location. So, the error message is displayed and the directory is created later.

$ cd newdir || mkdir newdir && echo “directory is created”

Combination operator <>

Two or more commands can be combined using this operator and if the execution of the first command fails then the second command will not execute. In the following example, OR, AND and combination operators are used together. First commands will check the temp directory is exist in the current location or not. If the first command fails then it will create a temp directory and print a message. The last command will show the current directory list.

Precedence operator ()

You can use this operator for grouping the commands at the time of execution. Here, each group will work as a single task. In the following example, two command groups are defined and if the first group fails to execute then the second group will execute.

$ (cd temp && ls -a) || (mkdir temp && ls)

Conclusion

This tutorial explained the mostly used operators for running multiple commands in Linux. But there are many others operators exist in bash which are used to run two or more commands together. These are ampersand (&), redirection ( ,>>), Logical NOT (!), Combination (<>) etc.

How do I run two commands in parallel Linux?

If you want the second command to only run if the first command is successful, separate the commands with the logical AND operator, which is two ampersands ( && ). For example, we want to make a directory called MyFolder and then change to that directory–provided it was successfully created.

How do I run a parallel script?

To run script in parallel in bash, you must send individual scripts to background. So the loop will not wait for the last process to exit and will immediately process all the scripts.

How do I run two shell scripts in parallel?

GNU parallel is a shell tool for executing jobs in parallel using one or more computers. A job can be a single command or a small script that has to be run for each of the lines in the input. The typical input is a list of files, a list of hosts, a list of users, a list of URLs, or a list of tables.

How do I run Unix commands in parallel?

You have various options to run programs or commands in parallel on a Linux or Unix-like systems: => Use GNU/parallel or xargs command. => Use wait built-in command with &. => Use xargs command.

What are commands?

A command is an order that you have to follow, as long as the person who gives it has authority over you. You don’t have to comply with your friend’s command that you give him all your money.

Does Xargs run in parallel?

xargs will run the first two commands in parallel, and then whenever one of them terminates, it will start another one, until the entire job is done. The same idea can be generalized to as many processors as you have handy. It also generalizes to other resources besides processors.

How do I run multiple python scripts in parallel?

For a more controlled way to run many processes in parallel, look into the Supervisor project, or use the multiprocessing module to orchestrate from inside Python. I had to do this and used subprocess. I do this in node. js (on Windows 10) by opening 2 separate cmd instances and running each program in each instance.

What is parallel SSH?

parallel-ssh is an asynchronous parallel SSH library designed for large scale automation. It differentiates ifself from alternatives, other libraries and higher level frameworks like Ansible or Chef in several ways: Scalability – Scales to hundreds, thousands, tens of thousands hosts or more.

How do I run multiple scripts in bash?

To run multiple commands in a single step from the shell, you can type them on one line and separate them with semicolons. This is a Bash script!! The pwd command runs first, displaying the current working directory, then the whoami command runs to show the currently logged in users.

How do I run multiple processes in Linux?

You can use the & to start multiple background jobs. This will start multiple jobs running in the background. If you want to keep a job running in the background, once you exit the terminal you can use nohup . This will ensure that SIGHUP , is not sent to a process once you exit the terminal.

What is wait command in Linux?

wait is a built-in command of Linux that waits for completing any running process. wait command is used with a particular process id or job id. … If no process id or job id is given with wait command then it will wait for all current child processes to complete and returns exit status.

What is && in bash?

4 Answers. “&&” is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0).

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint). Then, type the following three commands on one line, separated by semicolons, and press Enter.

How do I run two scripts at once?

3 Answers. Another option to running multiple scripts simultaneously is npm-run-all. And start with npm start as usual. You can start multiple application by using “pm2” node_module.

How do I run multiple shell scripts after one?

  1. With ; between the commands, they would run as if you’ve given the commands, one after the other, on the command line. …
  2. With && , you get the same effect, but a script would not run if any previous script exited with a non-zero exit status (indicating a failure).

How do I run multiple scripts in JSON?

How to run multiple NPM scripts in parallel

  1. Step 1: Install the concurrently NPM module. The first step is to install concurrently into your project, and save it as a dev dependency in your package. json file. …
  2. Step 2: Create your package. json dev scripts. …
  3. Step 3: Run your dev package. json script.

How do I run two npm scripts?

&& will run your scripts sequentially while & will run them in parallel. A quick way of doing it is npm run start-watch & npm run wp-server . This will run the first command as a background thread. This works really well when one of the commands is not long running and does not need to be manually exited later.

How do I run two shell scripts in parallel?

GNU parallel is a shell tool for executing jobs in parallel using one or more computers. A job can be a single command or a small script that has to be run for each of the lines in the input. The typical input is a list of files, a list of hosts, a list of users, a list of URLs, or a list of tables.

How do I run multiple parallel scripts in UNIX?

How can I run multiple programs in parallel from a bash script? You have various options to run programs or commands in parallel on a Linux or Unix-like systems: => Use GNU/parallel or xargs command. => Use wait built-in command with &.

How do I run multiple scripts in Nodejs?

npm run lint && npm run build && npm run api && npm run whereverthing :P. Then I found npm-run-all is a node package, it allows us to run all scripts defined in npm in sequential or parallel each one in parallel.

How do I run a script in json?

You can easily run scripts using npm by adding them to the “scripts” field in package. json and run them with npm run

In this article, we will show how to run commands on multiple Linux servers at the same time. We will explain how to use some of the widely known tools designed to execute repetitive series of commands on multiple servers simultaneously. This guide is useful for system administrators who usually have to check the health of multiple Linux servers everyday.

For the purpose of this article, we assume that you already have SSH setup to access all your servers and secondly, when accessing multiple servers simultaneously, it is appropriate to set up key-based password-less SSH on all of your Linux servers. This above all enhances server security and also enables ease of access.

1. PSSH – Parallel SSH

Parallel-SSH is an open source, fast and easy-to-use command line based Python toolkit for executing ssh in parallel on a number of Linux systems. It contains a number of tools for various purposes such as parallel-ssh, parallel-scp, parallel-rsync, parallel-slurp and parallel-nuke (read the man page of a particular tool for more information).

To install parallel-ssh, you need to first install PIP on your Linux system.

Then install parallel-ssh using pip as follows.

Next, enter the hostnames or IP addresses of remote Linux server with SSH Port in a file called hosts (you can name it anything you want):

Save the file and close it.

Now run parallel-ssh, specify the hosts file using the -h option and a command(s) that will be executed on all the specified servers. The -i flag means display std output and std error as execution of the command on each server completes.

Pssh Run Commands on Multiple Linux Servers

2. Pdsh – Parallel Remote Shell Utility

Pdsh is an open source, simple parallel remote shell tool for executing commands on multiple Linux servers at the same time. It employs a sliding window of threads to execute remote commands.

To install Pdsh on your Linux machines, run the appropriate command below.

To run commands on multiple servers, add the servers to a hosts file as explained before. Then run pdsh as shown; the flag -w is used to specify the hosts file, and -R is used to specify the remote command module (available remote command modules include ssh, rsh, exec, the default is rsh).

Take note of the ^ before the hosts file.

pdsh – Execute Commands in Multiple Linux Servers

In case you do not specify a remote command to be executed on the command line as shown above, pdsh runs interactively, prompting you for commands and running them when terminated with a carriage return. For more information, see the pdsh man page:

3. ClusterSSH

ClusterSSH is a command line tool for administering clusters of multiple servers at the same time. It launches an administration console and an xterm to all specified servers enabling you to run the same command on all of them.

To use clusterssh, start by installing it on your local Linux computer as shown.

Now that you have it installed, open an admin console and an xterm on remote servers at once, as follows. To run a command on all the servers, click in the xterm input bar, and type your command; to manage a single host, use its admin console.

Clusterssh – Administer Multiple SSH Sessions

For more information, see the clusterssh man page:

4. Ansible

Ansible is an open source and popular tool to automate IT processes. It is used for configuring and managing systems, deploying applications and so much more.

To install Ansible on Linux systems, run the appropriate command below:

Once you have installed ansible, you can add your server’s hostnames or IP addresses in the file /etc/anasible/hosts.

Specify them in groups, e.g webservers.

Save the file and close it.

Now to check the uptime and users connected to all the servers specified in the group webserver, in hosts config file above, simply run the ansible command line tool as follows.

The -a options is used to specify the arguments to pass to the module and -u flag specifies the default username to connect to the remote servers via SSH.

Note that the ansible CLI tool only allows you to execute at most only one command.

Ansible – Run Command on Multiple Linux Servers

That’s all! In this article, we have explained how to run commands on multiple remote Linux servers at the same time using widely used tools. If you know of any tools out there for the same purpose, that we have not included in this article, let us know via the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

I have a basic understanding of how to get a job in foreground switch to background and vice-versa but I am trying to come up with a way so that I can run multiple jobs in the background.I tried to put multiple jobs in the background but only one of which was in running state.I want to have a scenario where I can run multiple jobs in the background.

I came across this website where I see multiple jobs running in the background.Can someone please break it down for me as to how can I run multiple jobs in the background?

How to run two or more terminal commands at once in linux

3 Answers 3

You can use the & to start multiple background jobs.

Example to run sequentially:

Or run multiple jobs in parallel

This will start multiple jobs running in the background.

If you want to keep a job running in the background, once you exit the terminal you can use nohup . This will ensure that SIGHUP , is not sent to a process once you exit the terminal.

When you start a job with an & sign at the end, you send it into the background. You can have as many background jobs as you like.

When a background job requires terminal input, it is automatically suspended and you receive a notification about that, either before the next command prompt (i.e. after you have run another command), or immediately if you used set -b .

When you log out, all running background processes will be sent a signal to notify them that the terminal has gone away. The default behavior for this signal is to kill the process, but you can change this by starting the background job through the nohup command.

For long-running background jobs, you can also use the at command to have the command started by a separate daemon at a specific time (which can be now ). In this case, the output of the command will be sent to you by mail, but this requires the mail system on your computer to be set up properly.

Parallel processing is the concept of running multiple processes simultaneously. This concept is the crux of today’s modern computer systems. In the very same manner, multiple commands can also be made to run in parallel, and today, we will learn how to do this on a Linux Mint 20 system.

Methods of Running Multiple Commands in Parallel in Linux Mint 20

For running multiple commands in parallel in Linux Mint 20, you can make use of either of the following methods:

Method #1: Using the Semicolon Operator

For using the semicolon operator for running multiple commands in parallel in Linux Mint 20, you need to separate multiple commands that you want to run in parallel with semicolon in your terminal in the manner shown below:

Here, you can have as many commands as you want to run in parallel separated by semicolons.

When you press the “Enter” key to execute this statement in your terminal, you will be able to notice from the output that all of these commands have been executed in parallel, as shown in the following image:

How to run two or more terminal commands at once in linux

Method #2: Using a Bash Script

For using a Bash script to run multiple commands in parallel in Linux Mint 20, you will have to create a Bash file, i.e., a file with the “.sh” extension in your Home directory. You can name this file as per your preference. In our case, we have named it “Parallel.sh”. In this file, you need to state all those commands that you want to run in parallel in separate lines followed by the “&” symbol. We wanted to run the “ls” command thrice in parallel, as you can see from the image shown below:

After writing this script and saving it, you can execute it in the terminal with the following command:

When you hit the “Enter” key to execute this script, you will be able to analyze from the output that the specified commands in your Bash script have run in parallel, as shown in the image below:

How to run two or more terminal commands at once in linux

Conclusion

In this article, we taught you the two different methods of running multiple commands in parallel on a Linux Mint 20 system. The first method was quite simple as you simply had to run all the commands separated by semicolons in your terminal. However, for the second method, you had to create a Bash script for serving the very same purpose.

About the author

How to run two or more terminal commands at once in linux

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

Chaining commands in Linux allows us to execute multiple commands at the same time and directly through the terminal. It’s like short shell scripts that can be executed through the terminal directly. Linux command chaining is a technique of merging several commands such that each of them can execute in sequence depending on the operator that separates them and these operators decide how the commands will get executed. It allows us to run multiple commands in succession or simultaneously.

Operators

Function

Working with chaining operators

1. Ampersand(&) Operator: It is used to run a command in the background so that other commands can be executed. It sends a process/script/command to the background so that other commands can be executed in the foreground. It increases the effective utilization of system resources and speeds up the script execution. This is also called as Child process creation or forking in other programming languages. Ampersand sign can be used as follows:

2. AND (&&) Operator: The command succeeding this operator will only execute if the command preceding it gets successfully executed . It is helpful when we want to execute a command if the first command has executed successfully.

How to run two or more terminal commands at once in linux

3. Semi-colon(;) Operator: It is used to run multiple commands sequentially in a single go. But it is important to note that the commands chained by (;) operator always executes sequentially. If two commands are separated by the operator, then the second command will always execute independently of the exit status of the first command. Unlike the ampersand operator, the execution of the second command is independent of the exit status of the first command. Even if the first command does not get successfully executed i.e, the exit status is non-zero, the second command will always execute.

The three commands will get executed sequentially. But the execution of the command preceding ( ; ) operator will execute even if the execution of the first command is not successful.

4. Logical OR (||) Operator: The command succeeding this operator will only execute if the execution of the command preceding it fails. It is much like an else statement. If the execution status of the first command is non-zero then the second command will get executed.

How to run two or more terminal commands at once in linux

5. Piping (|) Operator: This operator sends the output of the first command to the input of the second command.

In the above command wc -l displays the number of lines. ls -l displays the lists the files in the system. The first command displays the number of files in the directory. ls – l lists the names of the files and this output is sent to the next command which counts the number of lines in the input. As a result, by using pipe we get the number of files in the directory.

6. NOT (!) operator: It is used to negate an expression in command/. We can use it to delete all files except one in a directory.

This command will remove all files in the directory except a.txt. In the image below, we create some files using the touch command inside a directory. ls shows the files in the directory. To delete all files except ‘a.txt’ we use! Operator. If we list the files again, we can see that all files except a.txt are removed.

7. Redirection Operators(‘ ’,’>>’): This operator is used to redirect the output of a command or a group of commands to a stream or file. This operator can be used to redirect either standard input or standard output or both. Almost all commands accept input with redirection operators.

The first command creates a file with the name ‘file_name’ (The redirection operator >> allows us to give input in the file) while the second command will sort the contents of the file. Refer to the image below, we first create a file with numbers and then use this command. This sorts the content of the files.

How to run two or more terminal commands at once in linux

8. AND, OR Operators as an if-else condition: This command can be used as an if-else statement. It is a combination of logical AND and logical OR operators.

This command will first check if the directory ‘ABC’ exists or not. If it does not exist then a new directory is created else ‘ABC’ becomes the current directory. Refer to the image below, the directory named ‘ABC’ does not exist and hence it is created. When the same command is executed the second time, then the directory already exists and hence ‘ABC’ becomes the current directory.

9. Concatenation Operator(\): Used to concatenate large commands over several lines in a shell. It also improves the readability for the users. A large command is split over several lines and hence, it is used to execute large commands.

It will open a file named text(1).

10. Precedence: This command is used to set precedent value so that multiple commands can execute in a given order.

In the first case, if the first command is successful then the second will get executed but the third command will not execute. But in the second case, the third command will get executed as the precedence is set using the () operator. Refer to the image below: If the directory exists (the first command), then the current directory becomes PQR (second command) but in the first case the third command is not getting executed while in the second case when the precedence operator is used then the third command is also executed.

11. Combination Operator (<>): The execution of the command succeeding this operator depends on the execution of the first command. The set of commands combined using <> operator executes when the command preceding it has successfully executed.

In the first case, hello will always get printed. If the file exists then the command will get executed as it is preceding the && operator. If we want to execute both second and third commands only if the file exists, then we use <> operators to combine the commands.

Linux: Why clutter up your desktop with separate terminal windows for every task? Learn to love GNU Screen , the terminal multiplexer, which essentially adds “tabs” to your terminal window. Here’s how to use it, and tweak it to be even better.

GNU Screen allows you to run multiple console applications within a single terminal window, and switch between them easily with the keyboard—but it gets even better: it also allows you to save your running session and come back to it later. So, for instance, you can remotely log in to another PC over SSH, open up a screen session, and keep your applications running there in a screen session even after you disconnect.

Using Screen Shortcuts

Once you’ve installed GNU Screen through your package manager and started a new screen session by simply typing screen at the terminal prompt, you’ll need to know how to use a couple of simple commands, all of which are preceded by the Ctrl+A key combination. So, for example, to create a new “window” within screen, you’d press Ctrl+A, and then press C.

Here’s a list of the most useful commands that you might need to use—you should enter these in lower case, they are simply shown here in upper case to make it more readable.

  • Create New Screen: Ctrl+A, C
  • Switch to Screen: Ctrl+A, N (where N is the number of the screen)
  • Switch to Next Screen: Ctrl+A, A
  • View List of Screens: Ctrl+A, W
  • View Screen Picker: Ctrl+A, ” (double quote)
  • Detach Current Session: Ctrl+A, Ctrl+D
  • Attach to Running Screen Session: screen -R
  • Show Shortcut Keys: Ctrl+A, ?

There’s loads of other commands that you can use to control your screen session, most of which can be accessed by typing Ctrl+A, ? at the prompt, which will bring up a help window that shows you all of the available bindings:

Save yourself time and effort when testing or varying input

If you’re using MacOS or a Linux-based OS, you have access to a powerful Terminal (using Bash or Z-Shell). On Windows, you have Windows PowerShell as an equivalent. Both are quite powerful if you know how to use them. Think of all the great CLIs (e.g. Angular CLI) that make the life of developers easier.

Sometimes you want to repeat certain code multiple times. In my case, I wanted to run the same script multiple times to verify that it works reliably. In most programming languages, like JavaScript, C#, or Java, you’d usually create a for or while loop to achieve this task.

In this piece, I want to show you how to do this in Bash and Windows PowerShell. Let’s have a look at some use cases:

  • If you have flaky tests that you want to fix, you need to run your tests multiple times in a row to make sure the tests work reliably
  • Running a command multiple times with different input
  • Reduce manual effort of rerunning the same commands

How to run two or more terminal commands at once in linux

  1. Wrap your statement for i in <1..n>; do someCommand; done , where n is a positive number and someCommand is any command.
  2. To access the variable (I use i but you can name it differently), you need to wrap it like this: $< i> .
  3. Execute the statement by pressing the Enter key.

How to run two or more terminal commands at once in linux

How to run a command multiple times in Windows PowerShell

  1. Wrap your statement inside the curly braces of for ($i=1; $i -le n; $i++) < someCommand> , where n is a positive number and someCommand is any command.
  2. To access the variable (I use i but you can name it differently) you need to wrap it like this: $i .
  3. Execute the statement by pressing the Enter key.

Thanks for reading this short piece. As you can see, it’s easy to run a command multiple times in a row in both Bash and PowerShell. Let me know what you think in the comments.

I have a few test scripts, each of which runs a test PHP app. Each script runs forever.

So, cat.sh , dog.sh , and foo.sh each run a PHP script. Each shell script runs the PHP app in a loop, so it runs forever, sleeping after each run.

I’m trying to figure out how to run the scripts in parallel at the same time. See the output of the PHP apps in the stdout/term window.

I thought, doing something like the following might work:

In a shell script it would be sufficient, but it’s not working.

It appears that the shell script never gets to run cat.sh . If I run cat.sh by itself in a separate window/term, it runs as expected.

Does anyone have any ideas on how I can get these scripts to run in parallel?

How to run two or more terminal commands at once in linux

5 Answers 5

Your current setup is running your commands sequentially. The first one runs, and completes, allowing the second one to start. The second one never ends, so the third one never gets a chance to start.

That will tell each command to run in the background, and send their output and error information to files. When a command is run in the background, it detaches from the current session, and allows the next command to run. It’s important to put the ampersand ( & ) as the last character of the line. Otherwise, it might not get recognized correctly.

Alternately, have each of your shell scripts run the associated .php script you’re apparently calling with the same semantics as above. In this scenario, your foo.sh might contain:

Finally, if you need true parallel operation, check out GNU Parallel.

Note: If you really want the output going to the screen/terminal, you can leave off the output redirection:

Remember, though, that running multiple commands concurrently can cause confusing output (you may now know what output or errors came from which command), and if you logout, the output has nowhere to go.

Take a look at the tools covered in the three previous articles, and you will see that understanding the glue that joins them together is as important as recognizing the tools themselves. Indeed, tools tend to be simple, and understanding what mkdir, touch, and find do (make a new directory, update a file, and find a file in the directory tree, respectively) in isolation is easy.

But understanding what

does, and why we would write a command line like that is a whole different story.

It pays to look more closely at the sign and symbols that live between the commands. It will not only help you better understand how things work, but will also make you more proficient in chaining commands together to create compound instructions that will help you work more efficiently.

In this article and the next, we’ll be looking at the the ampersand ( & ) and its close friend, the pipe ( | ), and see how they can mean different things in different contexts.

Behind the Scenes

Let’s start simple and see how you can use & as a way of pushing a command to the background. The instruction:

Copies all the files and subdirectories in original/dir/ into backup/dir/. So far so simple. But if that turns out to be a lot of data, it could tie up your terminal for hours.

pushes the process to the background courtesy of the final & . This frees you to continue working on the same terminal or even to close the terminal and still let the process finish up. Do note, however, that if the process is asked to print stuff out to the standard output (like in the case of echo or ls ), it will continue to do so, even though it is being executed in the background.

When you push a process into the background, Bash will print out a number. This number is the PID or the Process’ ID. Every process running on your Linux system has a unique process ID and you can use this ID to pause, resume, and terminate the process it refers to. This will become useful later.

In the meantime, there are a few tools you can use to manage your processes as long as you remain in the terminal from which you launched them:

jobs shows you the processes running in your current terminal, whether be it in the background or foreground. It also shows you a number associated with each job (different from the PID) that you can use to refer to each process:

fg brings a job from the background to the foreground so you can interact with it. You tell fg which process you want to bring to the foreground with a percentage symbol ( % ) followed by the number associated with the job that jobs gave you:

If the job was stopped (see below), fg will start it again.

You can stop a job in the foreground by holding down [Ctrl] and pressing [Z]. This doesn’t abort the action, it pauses it. When you start it again with ( fg or bg ) it will continue from where it left off…

…Except for sleep : the time a sleep job is paused still counts once sleep is resumed. This is because sleep takes note of the clock time when it was started, not how long it was running. This means that if you run sleep 30 and pause it for more than 30 seconds, once you resume, sleep will exit immediately.

  • The bg command pushes a job to the background and resumes it again if it was paused:
  • As mentioned above, you won’t be able to use any of these commands if you close the terminal from which you launched the process or if you change to another terminal, even though the process will still continue working.

    To manage background processes from another terminal you need another set of tools. For example, you can tell a process to stop from a a different terminal with the kill command:

    And you know the PID because that is the number Bash gave you when you started the process with & , remember? Oh! You didn’t write it down? No problem. You can get the PID of any running process with the ps (short for processes) command. So, using

    will show you all the processes containing the string “cp“, including the copying job we are using for our example. It will also show you the PID:

    In this case, the PID is 14444. and it means you can stop the background copying with:

    Note that STOP here does the same thing as [Ctrl] + [Z] above, that is, it pauses the execution of the process.

    To start the paused process again, you can use the CONT signal:

    There is a good list of many of the main signals you can send a process here. According to that, if you wanted to terminate the process, not just pause it, you could do this:

    If the process refuses to exit, you can force it with:

    This is a bit dangerous, but very useful if a process has gone crazy and is eating up all your resources.

    In any case, if you are not sure you have the correct PID, add the x option to ps :

    And you should be able to see what process you need.

    Finally, there is nifty tool that combines ps and grep all into one:

    Lists all the PIDs of processes that contain the string “cp“.

    In this case, it isn’t very helpful, but this…

    In this case, -l tells pgrep to show you the name of the process and -x tells pgrep you want an exact match for the name of the command. If you want even more details, try pgrep -ax command .

    Next time

    Putting an & at the end of commands has helped us explain the rather useful concept of processes working in the background and foreground and how to manage them.

    One last thing before we leave: processes running in the background are what are known as daemons in UNIX/Linux parlance. So, if you had heard the term before and wondered what they were, there you go.

    As usual, there are more ways to use the ampersand within a command line, many of which have nothing to do with pushing processes into the background. To see what those uses are, we’ll be back next week with more on the matter.

    In Linux, to perform any task, we need to execute the appropriate commands on the terminal. In case you need more efficiency, you can run multiple commands simultaneously in Linux. This post will quickly teach you how we can run multiple commands in Linux depending on different situations or conditions.

    How do I run multiple commands in Linux at the same time?

    There are several operators available to run multiple commands in Linux at the same time, such as the semicolon or;, the logical AND operator, and the logical OR operator.

    Use the semicolon operator “;”

    Semicolon or “;” operator allows you to run multiple commands at the same time in Linux, when the command is separated by “;”.

    Basic syntax for the semicolon operator:

    It doesn’t matter if the previous command is successful or not. Even if one command fails, the next command will be executed. This is very useful in shell scripting.

    Using the logical operator “&&”

    Sometimes we only need to execute the second command if the first command completed successfully, as opposed to the semicolon operator.

    Basic syntax of a logical operator:

    An example of a logical operator.

    In the above example, we created a folder or directory named “data” under the directory section “/ tmp”. Since we have successfully created the / tmp / data directory, we may be able to change to the “/ tmp / data” directory.

    In order to double-check this condition, run the same command again, as shown below:

    In the above command output, “mkdir / tmp / data” failed because it already exists. The system does not allow the second command to run.

    The logical AND operator is recommended over the semicolon operator, as it will check the success or failure status of the previous command. To explain this, let’s look at an example.

    1. Go to the directory / tmp / data1
    2. Delete all files in it.

    Here, in the above example, executing the command “cd / tmp / data1; rm -rf *” in parallel led to a catastrophe, since the system directory / tmp / data1 does not exist, and therefore instead of deleting files in / tmp / data1 / will delete all of our files in the current working directory that are located in / tmp / data. To avoid this situation use the commands below with the logical operator “cd / tmp / data1 && rm -rf *”.

    Here the second team failed, as the first team also failed.

    Using the logical OR operator “||”

    In some other cases, we have to execute the second command only if the first command failed. To handle this we use the logical OR operator.

    Basic syntax for logical OR operator:

    An example of a logical OR operator.

    Here we have only created the directory “/ tmp / data1” in the second command, only if it does not exist, which is checked in the first command “[-d /tmp/ data1]”.

    Combining multiple statements to execute multiple commands in Linux

    We can also combine multiple statements to run multiple commands in Linux.

    We have used multiple operators in the above command. In case the file exists, we will receive a message like this “successfully opened the file” otherwise we will receive the error “Could not open the file”. This way we can combine multiple statements at one time to run multiple commands in Linux.

    Best methods to run multiple commands in CMD!

    If you have been using Windows 10 for a while, you might know about the Command Prompt. Command Prompt is one of the best utilities of Windows 10 that allows you to automate and complete a wide range of tasks.

    There are plenty of things that you can do with the command prompt. For example, you can utilize the best CMD commands to perform basic stuff. Similarly, there are times when we want to run multiple commands on Command Prompt.

    You can execute multiple commands on the Command prompt, but you need to do it manually. What if I tell you that you can run multiple commands at the same time in Command Prompt?

    2 Best Methods to run Multiple Commands in CMD

    Yes, you can run two commands in one line in Windows Command Prompt. For that, you need to create a batch script file using Notepad. Below, we have shared the two best methods to run multiple commands in CMD on Windows 10 computers. Let’s check out.

    1. Using Notepad

    This method includes creating a batch script to run multiple commands. Using this, you can execute all your commands one by one automatically. For that, we are going to use the commands to reset the DNS cache of Windows 10 –

    • ipconfig /displaydns
    • ipconfig /flushdns
    • ipconfig /release
    • ipconfig /renew

    Step 1. First of all, open the Notepad on your computer.

    How to run two or more terminal commands at once in linux

    Step 2. Now enter the commands that you want to execute in a single click. In this example, we are using the four commands which we have mentioned above.

    How to run two or more terminal commands at once in linux

    Step 3. Next, click on the file and select the ‘Save as’ option.

    How to run two or more terminal commands at once in linux

    Step 4. Now save this file with the .bat extension. For example, DNSreset.bat

    How to run two or more terminal commands at once in linux

    Step 5. If you wish to reset the DNS cache, double click on the batch script file.

    How to run two or more terminal commands at once in linux

    That’s it! You are done. This is how you can run multiple commands in Command prompt.

    2. Using Special Characters

    In this method, we will use some special characters in between the commands to execute them at the same time. Follow the steps given below.

    Step 1. If you want to run two or more commands simultaneously, just insert the “&” between the commands. For example – ipconfig /flushdns & ipconfig /renew

    How to run two or more terminal commands at once in linux

    Step 2. If you want to execute the second command after the success of the first command, then use the “&&” between the commands. For example – ipconfig /flushdns && ipconfig /renew

    How to run two or more terminal commands at once in linux

    Step 3. If you want to run the second command only if the first one has failed to execute, then enter “||” between the commands. For example – ipconfig /flushdns || ipconfig /renew

    How to run two or more terminal commands at once in linux

    That’s it! You are done. You can use these signs in between commands as per your wish.

    So, this article is all about how to run multiple commands in CMD on Windows 10. I hope this article helped you! Please share it with your friends also. If you have any doubts related to this, let us know in the comment box below.

    How to run two or more terminal commands at once in linux

    Introduction to Exec Linux

    In the Linux environment, we need to work on different applications and job levels. The number of times we need to run the jobs or the shell or bash job in terms of the command. The exec will make the command for the bash job. If we are running the bash command multiple times then it will create multiple processes in the background. But if we are running the bash job with the help of the exec command then it will not create multiple processes on the Linux environment. When we are executing the bash job as a command with the help of the Linux exec utility then we are not able to return or call the process.

    Syntax of Exec Linux

    Web development, programming languages, Software testing & others

    exec [ -cl ] [ -a name ] [ command [ arguments ] ] [ redirection . ]

    1) exec: We can use the exec keyword in the syntax or command. It will accept different arguments like name, command, different arguments, etc. As per the provided input, the exec will be able to convert the bash shell job into a specific command. The command can run differently in the Linux environment. Here, there is no need to run the bash or shell job. We can directly run the command. It will run the specific process on the environment. The exec commands will help to manage the different bash-related tasks or jobs.
    2) OPTION: There are multiple options available for the Linux exec. We can use different options like empty environment (-cl), name, different commands, arguments, etc. As per the requirement, we can use the different flags as the option that is compatible with the exec command.
    3) Redirection: As per the requirement, we can use the different redirection options in the exec command.

    How Exec Linux Works?

    In the Linux environment, we are having multiple applications and jobs that are running on it. When we are having multiple bash jobs or scripts. It will very difficult to manage multiple jobs when we are running manually. To avoid it, we need to handle this condition with the help of the exec command. Here, we need to replace the specific command with the specific bash value. It will help to manage the number of bash files or jobs with the specific command.

    Below is the list of options that can be used in the exec command.

    1. –p: It will print the name of the readline function and bindings. It will define in such a way that they can be re-read.
    2. –l: It will help to list all the names of readline functions available in the environment
    3. –P: It will print the current list of readline function names and bindings.
    4. – s: It will print the readline key sequences which are bounded to the macros. The string output that they can be re-read.
    5. –S: It will display the readline key sequences which are bounded to the macros. The strings are related to the output.
    6. –v: It will print the list of readline variable names and values in such a way that they can be re-read.
    7. –V: It will display the current readline variable names and the values.
    8. -f filename: It will read key bindings from the filename.
    9. -q function: It is related to the query about which keys invoke the function name.
    10. -u function: It will unbind all keys bound to the named function.
    11. -r keyset: It will help to remove all the current binding of the keyseq.
    12. -x keyseq : shell-command: Whenever the keyseq is extended then the shell-command is to be executed. When the shell-command is executed, the shell sets in the READLINE_LINE variable. The content of the readline is the buffer. The READLINE_POINT is the variable to the current location (the insertion point). If we have executed the command changes then the value of READLINE_LINE or READLINE_POINT and the new values will be reflected in the editing state.
    13. -C command: It will help to run the command is executed in a subshell environment. The output is used as the possible completions.
    14. -F function: With the help of this option, the function is executed in the current or working shell environment. When the function execution is completed then the possible completions are retrieved from the COMPREPLY array variable.
    15. -G globpat: With the help of this option, the pathname expansion pattern for the globpat is expanded to generate the possible completions.
    16. -P prefix: We can add the prefix at the beginning of each possible completion. After all, are the other options have been applied.
    17. -S suffix: With the help of this option the suffix is appended to each possible completion. After all, are the other options have been applied.
    18. -W wordlist: With the help of this option, the list is split using the characters in the IFS special variable as delimiters. Once the list will split and each resultant word is expanded then the possible completions are the members of the resultant list which match the word from the beginning.
    19. -X filterpat: With the help of this option, we can filter part of the pattern as used for pathname expansion. It will be able to apply the list of possible completions generated by the preceding options and the arguments. Each completion will match the filter part and remove it from the list.

    Example

    Exec Linux: Work with the exec command. In the Linux environment, we are able to run the bash shell with the help of the exec command.