Linux execute multiple commands

Execute combine multiple Linux commands in one line

If you want to execute each command only if the previous one succeeded, then combine them using the && operator:

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install 

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:

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install 

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:

#! /bin/sh cd /my_folder \ && rm *.jar \ && svn co path to repo \ && mvn compile package install 

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.

A more convenient way compared to using backslashes and && everywhere is to instruct the shell to exit the script if any of the commands fail. You do that using the set built-in function with the -e argument. With that, you can write a script in a much more natural way:

#! /bin/sh set -e cd /my_folder rm *.jar svn co path to repo mvn compile package install 

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 don’t call set -e :

#! /bin/sh cd /my_folder rm *.jar svn co path to repo mvn compile package install 

Источник

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:

But if I want to run multiple commands in background, I tried the following command format, but failed:

Читайте также:  Redo backup and recovery linux

Panther, it seems using () could help fix this issue much easier than using a script. Let’s try to make full use of the features provided by the shell itself firstly, instead of composing what we want by ourselves. But of course, using script also could fix this issue. Thanks anyway.

What if I want to run a ‘tail -F > ‘ followed by ‘jobs -l’, which is again followed by ‘disown -h %1’

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):

() could help bash to distinguish the & and &&. So just use () to seperate the execution unit when we want to use the & and && togather.

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: ; & && || :

command1 ; command2 # runs sequentially command1 && command2 # runs sequentially, runs command2 only if command1 succeeds command1 || command2 # runs sequentially, runs command2 only if command1 fails command1 & command2 # runs simultaneously 

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:

# if c1 succeeds start a shell in the background # and run c2 and c3 sequentially inside it c1 && ( c2 ; c3 ) & # run c1 and if it succeeds c2 sequentially as a group command # if c1 or c2 fail run c3 in the background < c1 && c2 ;>|| c3 & 

This can get quite complicated, if you’re unsure use true and false to test whether the construction works as expected:

Читайте также:  Изменить версию python по умолчанию linux

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:
 % # last process in the jobs list %1 # 1st process in the jobs list %abc # process beginning with the string “abc” %?abc # process containing the string “abc” anywhere 
 %& # last process in the jobs list %1& # 1st process in the jobs list %abc& # process beginning with the string “abc” %?abc& # process containing the string “abc” anywhere 
 wait %1 # 1st process in the jobs list 

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:

 wait %3 || echo failed ; systemctl suspend 

Источник

How to run multiple commands in Linux

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

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.

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.

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.

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.

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.

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.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector