- How to Run Multiple Linux Commands at Once in Linux Terminal [Essential Beginners Tip]
- Using ; to run multiple Linux commands in one line
- Using && to run multiple Linux commands
- Using || to run several Linux commands at once
- Bonus Tip: Combine && and || operators
- Running multiple commands in one line in shell
- 6 Answers 6
- How can I run multiple commands which have & in one command line?
- 2 Answers 2
- Lists
- Job Control
- Which one is better: using ; or && to execute multiple commands in one line?
- 7 Answers 7
- Execute combine multiple Linux commands in one line
- 11 Answers 11
How to Run Multiple Linux Commands at Once in Linux Terminal [Essential Beginners Tip]
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.
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.
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:
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.
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:
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 multiple commands in one line in shell
Say I have a file /templates/apple and I want to
- put it in two different places and then
- remove the original.
So, /templates/apple will be copied to /templates/used AND /templates/inuse and then after that I’d like to remove the original.
Is cp the best way to do this, followed by rm ? Or is there a better way?
I want to do it all in one line so I’m thinking it would look something like:
Is this the correct syntax?
6 Answers 6
You are using | (pipe) to direct the output of a command into another command. What you are looking for is && operator to execute the next command only if the previous one succeeded:
To summarize (non-exhaustively) bash’s command operators/separators:
- | pipes (pipelines) the standard output ( stdout ) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen to be.
- |& pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
- && executes the right-hand command of && only if the previous one succeeded.
- || executes the right-hand command of || only it the previous one failed.
- ; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.
Источник
How can I run multiple commands which have & in one command line?
I’ve encountered a headache problem.
I want to execute mulitple commands in background, so I want to start them in bash one by one. It’s easy to start one command in linux shell in background, just like this:
It’s also easy to start multiple commands, just like this:
But if I want to run multiple commands in background, I tried the following command format, but failed:
Both formats fail. How can I run multiple commands which have & in one command line?
2 Answers 2
If you want to run them sequentially:
If you want them to run parallel:
In bash you can also use this (space behind the < and the ; are mandatory):
I suppose you want this:
This starts myCommand1 and sends it to the background as it’s followed by ampersand, then immediately starts myCommand2 and sends also this to the background, therefore releasing the shell again.
Lists
For better understanding you may substitute pipeline by command here.
A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or .
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
AND and OR lists are sequences of one or more pipelines separated by the && and || control operators, respectively.
Source: man bash
Let’s break that down into examples. You can build a list by combining commands and separating them with one of these: ; & && || :
You can terminate lists with one of these: ; & .
Normally you execute a command or a list by pressing Enter , that equals . The semicolon ; serves the very same purpose especially in scripts. Ampersand & however starts the command(s) in a subshell in the background, immediately releasing the shell.
You can use round () or curly brackets <> to further group lists, the difference being that round brackets spawn a subshell and curly ones don’t. Curly brackets need a space after the first and a semicolon or a newline before the closing bracket. For example:
This can get quite complicated, if you’re unsure use true and false to test whether the construction works as expected:
Job Control
The jobs command displays a list of the background jobs that are running or have recently been finished in the current shell. There are a number of keyboard shortcuts and commands for job control:
- Ctrl + Z types the suspend character that causes the process currently running in the foreground to be stopped, it is not terminated, but remains in the jobs list
- Ctrl + Y types the delayed suspend character that causes the process currently running in the foreground to be stopped when it attempts to read input from the terminal
fg = % brings a process into the foreground starting it if necessary, you can specify the process as follows:
bg = %& takes a process into the background starting it if necessary:
wait waits for a background process to be finished and returns its termination status:
Imagine you started a lengthy process ( jobs reveals it’s number 3) and then realize you want the computer to be suspended when it finishes, plus echo a message if the process didn’t succeed:
Источник
Which one is better: using ; or && to execute multiple commands in one line?
In tutorials and how-to’s I often see commands combined. For instance,
The following questions deal with the difference between the two connectors, but do so mostly in the comments:
So here are a number of related questions:
7 Answers 7
&& only runs the second command if the first one exited with status 0 (was successful). ; runs both the commands, even if the first one exits with a non zero status.
Your example with && can be equivalently paraphrased as
Using ; will execute the commands irrespective whether first command is successful or not.
Using && will execute the second command only when first command executed successfully (status 0).
Both are used on different perspective. Like for a longer process, say for an installation you need to compile and install it. you should make && make install . So the install will run only if make successful.
So for dependent commands you should use && .
Wring bash, or commands with independent commands, use ; .
So if you want to shutdown computer even the first job failed use ; , but if want on complete success of first job initiate the shutdown use && .
a ; b will run b regardless of the exit status of a. a && b will run b only if a succeeded.
This is necessary and sufficient to answer to the first 3 questions. In particular, the 2 is too broad, and cannot be given «one» definitive answer — your best bet is to decide on a case by case basis.
As for the 4th question: They’re Bash syntax.
There is no intrinsic danger in using either. Again, the definition above is sufficient. It implies that you will write && when b has unintended effects if a does not succeed. There is no need for further rules or explanation, IMHO.
Kudos to Jack’s cheatsheet for saying how this works clearly and succinctly. But all of these things have a more general reason for being chosen. You don’t just have to memorize these facts for when you’re doing stuff in the shell. For more context you might also like to know that:
- ; is commonly used as a statement separator in languages like C, C++, Perl, Java, C#, awk, and a slew of languages that have been derived from those. It performs the same function in all of those: do one thing, then the next. It is like a period at the end of a sentence.
- & is used in C for bitwise AND so && was used for logical AND. Logically ANDing things in C includes a feature called shortcutting. Shortcutting means that for an AND that if the first thing is false there’s no reason to check the second thing. A single false item in an AND means the whole thing will be false. In the shell that means it won’t go onto the second command if the first one fails. Or if the first thing worked, it will go onto the second thing to see if it «might be false».
- | is used in C for bitwise OR so || is used for logical OR. Logical OR’s also feature shortcutting. In an OR this means that you look for the first true thing. So if the first thing fails it will try the second thing.
Источник
Execute combine multiple Linux commands in one line
I am trying to merge multiple linux commands in one line to perform deployment operation. For example
11 Answers 11
If you want to execute each command only if the previous one succeeded, then combine them using the && operator:
If one of the commands fails, then all other commands following it won’t be executed.
If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:
In your case, I think you want the first case where execution of the next command depends on the success of the previous one.
You can also put all commands in a script and execute that instead:
(The backslashes at the end of the line are there to prevent the shell from thinking that the next line is a new command; if you omit the backslashes, you would need to write the whole command in a single line.)
Save that to a file, for example myscript , and make it executable:
You can now execute that script like other programs on the machine. But if you don’t place it inside a directory listed in your PATH environment variable (for example /usr/local/bin , or on some Linux distributions
/bin ), then you will need to specify the path to that script. If it’s in the current directory, you execute it with:
The commands in the script work the same way as the commands in the first example; the next command only executes if the previous one succeeded. For unconditional execution of all commands, simply list each command on its own line:
Источник