Linux several commands in one line

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.

Источник

This post and this website contains affiliate links. See my disclosure about affiliate links.

how to chain commands in linux command line (with examples)

Sometimes you would want to run multiple commands in succession or simultaneously. This is usually useful when running processes or commands that is expected to run for a long period of time. This allows you to automate a process that include several commands that may or may not depend on the result of the previous command.

Linux command chaining is the method of combining several different commands such that each of them can execute in succession based on the operator that separate them. The important part of chaining is the operators that you use to combine them. These operators determine how the commands execute.

First, we will take a quick look at all the commonly used operators and its function. Later we will see examples on how it can be used with various commands. So, the list of operators are described below with the notations in brackets. This set of operators are used mostly to combine different commands and are easy enough to use directly from command line.

  • Logical AND (&&) : This command that follows this operator will execute only if the preceding command executes successfully.
  • Logical OR (||) : The command that follows will execute only if the preceding command fails.
  • Semi-Colon (;) : The succeeding commands will execute regardless of the exit status of the command that precedes it.
  • Pipe (|) : The output of the previous command acts as the input to the next command in the chain.
  • Ampersand (&) : This sends the current command to the background.
  • Redirection (>, >) : The operator can be used to redirect the output of a command or a group of commands to a stream or file.
Читайте также:  Линукс дистрибутивы похожие mac os

The above set are the most commonly used operators. However, there are several more that you probably should know. These set of operators are more of conditional in nature, or are used for grouping. They are very useful when writing long and complicated set of commands. They are therefore much more commonly found in shell scripts.

  • Logical NOT (!) : This is an operator that is more useful when you want to negate an expression with in a command.
  • AND-OR (&& — ||) : This combination of AND and OR operators can be used to create an if-then-else condition.
  • Concatenation (\) : This is useful when you have to split the command between multiple lines.
  • Precedence () : This allows several commands to be grouped, and all of the grouped commands are executed in a sub-shell.
  • Combination (<>) : This can be used to group commands into different sets and the commands are executed within the same shell.

Now, let’s look at some examples that will describe the function of these operators better. We will look at mostly some practical examples that you can use from the command line. We will use the operators one at a time and in combinations to simulate “real” world examples. Also, remember that each of these operators can be used within the shell script just as you use it directly from the command line.

Logical AND Operator

The logical AND operator will execute the commands that follow only if the current command is successful.

The rm command will execute if and only if the cd command is successful. If for some reason, the cd command fails, this will make sure that the files in another directory (the current working directory) won’t be accidentally deleted. You can chain several different commands using the AND operator.

/workspace/project/ && svn up && mvn clean install
bash$ cd /usr/src/linux && make && make modules_install && make install

The above two examples show how you can automate a compilation processes for your projects. Using the && operator makes sure that every command in the chain succeeds. This is probably the most used operator, especially in the command line.

Logical OR Operator

The logical OR operator acts quite the opposite to the AND operator. The command that follows will only be executed if the preceding command fails or the exit status is non-zero.

bash$ grep -nH apache /etc/passwd || grep -nH apache /etc/group

The grep command first checks if there is a user named apache (searches the passwd file). If it cannot find a user, then it will search if there is a group named apache in the group file.

bash$ find /usr/bin/ -iname «netstat» || find /sbin/ -iname «netstat» || find /bin/ -iname «netstat»

The above command searches different folders one after an other, till it finds the file by that name.

Semi-Colon Operator

This is useful when you want to execute a bunch of commands in succession and does not care about the exit state of the commands. This works best when the commands does not depend on the previous commands.

bash$ svn up; mvn clean install; rm -fr /tmp/*

The above commands will all execute no matter what. The mvn will clean and install even if the subversion (svn) fails to update successfully. Also, the rm command will clean up the /tmp/ folder regardless of the exit state of mvn.

Pipe Operator

The pipe operator is useful when the second command wants to use the output of the first command as its input.

bash$ ls -l /path/ | grep -i filename.txt

The above command can probably be done in many different ways, but it shows you how the pipe operator works. The output of the command ls -l /path/ is used by grep as its input. So, the above command will print out all the files in the directory /path that match the name filename.txt.

Ampersand Operator

The ampersand operator at the end of the commands will run the command in the background. You can run multiple commands in the back ground too, if you append each of them with the ampersand operator

/documents/ & shred -uz

/importantfiles/ & rm -r /tmp/*.txt

The above command will run the rm command to remove the files from the documents/ folder, while shredding the files in the importantfiles/ folder. This is a useful method when you want to run multiple commands simultaneously or at the same time.

Redirection Operators

The redirection operators can be used when you want to use a file or I/O stream other than the default standard input and standard output. You can use these operator to redirect either the standard input, standard output or both. Almost all commands will accept input using redirection operators.

Читайте также:  Строка поиска приложений alt linux

The above command will sort the contents of the file, named inputfile.txt. It will print out the sorted content into the standard output or the screen.

The above command will save the output of the ls command into a file name filelist.txt. It is useful in couple of different scenarios: if you want to view the output at a later time or if the output is too long to fit into a screenful or so.

bash$ sort outputfile.txt

You can use both the input and output redirection operators together in the command. The above sort command will take the contents of inputfile.txt, sort them and then save them as outputfile.txt.

The other redirection operator is >>, which works exactly like the > operator but will append the output to the file rather than overwriting the output file stream.

The above six operators are probably the ones that you will regularly use from command line. As I mentioned, there are more that you can use, but they are usually useful when writing much more advanced shell scripts rather than having to type it out in the command line.

Источник

Using Linux in command line

Files and directories in Linux

The file systems in Linux machines are based on hierarchical directory tree. There is one root directory in to which you can refer with slash sign (/). All the files and directories locate in the subdirectories of this directory so that each file has a unique combination of name and directory path. Also the commands that user gives are executed in a directory in which user currently is called current working directory.

Normally you do not need to know the explicit directory paths when you work in the CSC environment. It is enough to know the locations of the files in users own disk areas. The user and project specific disk areas are presented in chapter 3. However, you should remember that many disk areas in CSC environment can be accessed from several different servers (e.g. the users home directory) while some areas are server specific. In the case of shared disk areas the path to a certain file may be different in different servers.

Structure of linux commands

Once the terminal connection to CSC, e.g. to [Puhti-shell], has been opened, the remote server is used with Linux commands. The standard structure of a command is:

command -options argument1 argument2 .

The command is executed by pressing the return key (Enter). The names and functions of options and arguments depend on the linux command. In many cases you can run the command without any options and arguments. Options are used to modify the actions that the command performs. Arguments are used to define the files, directories and values that are used as input parameters and to define where the output is written.

For example command ls can be used as such or with several options and arguments. Running plane command ls lists the content of a directory in alphabetical order. You can modify the output of the command for example by using option -t . With this option the directory content list is ordered by the age of the file (time stamp). If no argument is given, ls prints out the content of the current working directory. By giving an argument to the ls command, user can define a directory which content should be listed. For example command:

ls -t /scratch/project_2979797

will list the content of directory /scratch/project_2979797. In case the command, argument or options contain errors, the command will not be executed when the return key is pressed. Instead an error message is printed to the screen. Thus having errors in the command normally does not cause any major problems. The output of commands depends on the command but in many cases, no output means that command was successfully executed.

Most of the Linux commands have their own manual page that can be studied with man command. For example the manual page of ls command could be studied with command:

The manual pages can be very detailed and technical. However, often you do not need to read and understand all the details on the manual pages, but instead you can just see what command line options are available for the given command, which are of interest for you and then start testing/using them in practice.

Often the most difficult thing in using Linux is knowing the name of suitable command. Below we introduce to the most frequently used linux commands. You can also use command apropos to find suitable command. Apropos lists those Linux commands whose short description lines match the text that is given as a command argument. For example to look for commands that are processing pdf files you could give command:

Note that the listing that apropos prints out includes only linux commands but not application program names. Thus, the sample command above would produce a list that contain many pdf conversion commands but not the pdf viewing programs like acroread or evince .

Basic commands for using directories

Table below lists the commands that are most frequently used for moving in the directory hierarchy and managing it. Below are some examples of directory related commands.

Читайте также:  Аналог delphi для linux

Basic directory commands

Name Argument Description
cd directory Change current working directory
ls directory Lists the content of a directory
pwd Print the directory path of current working directory
mkdir directory Create a new directory
rmdir directory Remove a directory

When you log in to a server at CSC, you will first locate in your home directory. You can check your location i.e. the path of the current working directory with command pwd (abbreviation from Print current Working Directory). However, you do not have to remember the location of your home directory (see cd command).

The content of the directory can be listed with a command ls . Plain ls command just lists the names of the files and directories in your current directory. You can get more information about the files and directories with command ls -la . The -l option produces long directory listing that in addition to the name contains also information of accession settings, size and the modification dates of the files and directories. The option -a defines that all files, including also the settings files that start with dot (.) character, are listed. Below is a sample output for ls -la command:

The first output row: total 26914 tells that the total size of the files in the directory is 26914 KB. In the list, the first character tells if the item is a file (-) or directory(d). The next nine characters display the access permissions of the files (see the chmod command for more details). The next columns show the number of links pointing to the item, owner, user group, size in bytes, modification time and finally the name of the file or directory.

By default the files are presented in alphabetical order. You can order the results by the modification time with option -t or by size with option -S (note: upper case S, not lower case s). Two other frequently used options are -h (Human readable) which prints out the sizes of larger files in megabytes or gigabytes and -r which means reverse sorting order. For example command:

is very handy when you want to check what files have recently been modified or created. ls and pwd commands do not modify your files in any way so you can use them always when you want to know where you are and what files your current directory includes.

Command cd directory_name moves you from the current directory to a directory you specified. For example the user kkayttaj could go to his local temporary directory with command:

In the latter command automatically defined environment variable $TMPDIR, that contains the explicit directory path, is used to define the target directory.

New directories can be created with a command mkdir directory_name. For example command:

Creates a new directory called project1. You can use ls command to check that the directory was created. Now you can go to this directory with command:

You can come back from the project1 directory with command:

Note the space between cd and the dots in the command. One dot ( . ) and two dots ( .. ) have special meaning in the Linux commands. One dot ( . ) means the current directory and two dots ( .. ) mean the directory that is one step lower in the directory tree i.e. the directory where current directory locates. Executing the cd command without any arguments will always move you back to your home directory, regardless where you are in the directory tree. An empty directory can be removed with command rmdir directory_name. For example:

Basic commands for files

In a very basic level a file in a Linux system is just a string of bytes, were a byte consists of eight bits. So called text files the contain only bytes that can be interpreted as text characters using ASCII coding. Thus these files can be considered to consist of lines of text. In so called binary files, also non-ASCII bytes are used and the text can’t and is not intended to be converted to text. Typical examples of binary files are compiled programs, images or compressed files. Normally users work mostly with text files and also in the examples of this guide we normally assume that the files contain some kind of text data: letters or numbers.

Each file has a name. Name can in principle be any combination of characters. However, several characters have special meaning e.g. ?, * and # , see below and thus using these characters in file names may cause problems. We recommend that you use only normal letters (lower or upper case), numbers, dot ( . ), dash ( — ) or under score ( _ ) characters in file and directory names at CSC. Also the space characters in file names cause often problems. We recommend that the space characters are replaced with underscores, for example: new_file.txt. Note that Linux is case sensitive: lower and upper case characters are not considered equal and for example names New_File.txt and new_file.txt refer to different files.

In linux, usage of name extensions like .doc or .txt is not obligatory. Most of the linux tools do not require specific extensions to be used. However, on the long run, using systematic naming conventions, including illustrative name extensions, makes the file management easier.

File related commands:

Print the content of the specified file of files to the standard output (your screen)

Источник

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