Linux skills (6): the function of & at the end of the command &&, |, ||, ;, (), &>, 2>&1 usage and difference, very practical

foreword

When using Linux commands, &&, ||, ;, () are occasionally encountered. What is the effect of the single " & " symbol at the end of the command, and what is the difference between these commands? Let's learn together.

bin/zookeeper-server-start.sh config/zookeeper.properties &

 [PS]: If you are interested in Zookeeper learning : ZK download and installation and true/false cluster construction , click to enter.

1. At the end of the command, the function of a single " & "

1.1, the role of &

Function: Indicates that the task is executed in the background , even if the ssh window is closed, the service will continue to run in the background.

Syntax format: command1 &

Note: By default, the process is the foreground process, and the Shell is occupied at this time, and the Shell window cannot perform other operations at this time. Usually, for those processes without interaction, many times, we want to start them in the background. At this time, we can add a '&' or ' -d ' at the end of the parameter to achieve this purpose.

#docker run -d -p 8000:8080 tomcat 后台阻塞运行(如果没有-d,窗口被关闭,服务也会随之关闭)

Of course, the two can also be used in combination , for example: ./MediaServer -d & 

Extension: The difference and connection when using the -d or & parameter to start the service alone 1. When the -d parameter starts the service, the service will run in the background as a daemon process and redirect the output to the system log or the specified log file 2. When using & to start the service, the service will run in the background as a background process , and the output will be redirected to the standard output outside the terminal. The output information of the service process can only be closed in the terminal You can view it before , and you cannot view it again after that;

3. When the -d parameter starts the service, you can use the service command to view and manage the service, including viewing the service status, restarting the service, etc.;
4. When using & to start the service, if you need to view the service status or stop the service, you need to use the ps command and The kill command is more cumbersome. 

[PS]: If you are interested in learning about Docker : the use of Docker commands , click to enter

1.2, the role of nohup

nohup is the abbreviation of no hang up, that is, it means no hang up. After closing the terminal interface, the process continues to run in the background.

Syntax format: nohup Command [ Arg ... ] [  &

Precautions:

1) When using the nohup command, you need to add & ("and" symbol) to the end of the command.

2) When using the nohup command, if you use ctrl + c or ctrl + z directly in the shell, the process will end ! ! ! .

3) The nohup command outputs the redirection directory by default, which is in the nohup.out file of the current directory; if the nohup.out of the current directory is read-only, the output is automatically redirected to the $HOME/nohup.out file. 


[root@centOS7 ~]# nohup ./startup.sh >output 2>&1 & 

Expansion: tomcat, nginx, etc. all start services through startup.sh .

Second, the role of the " && " command

Function: It means that the next command will be executed only when the previous command is executed successfully; otherwise, if the previous command fails to be executed, the command after && will not be executed.

Syntax format: command1 && command2   [&& command3 ...]

example 

[root@centOS7 ~]# data && echo hello
bash: data: 未找到命令...
[root@centOS7 ~]# date && echo hello
2022年 10月 17日 星期一 00:07:01 CST
hello

Note: Its feature is " the next command depends on whether the previous command is executed successfully  ", so they are often found in some combination commands that are closely related.

For example: To install expect , you need to install the dependencies first . If it is combined into one command, && is used at this time. 

3. The role of " | " pipeline

Function: | Indicates a pipeline, the output of the previous command is used as the parameter of the next command, and is usually used to filter/summarize data.

Syntax format: command1 | command2   [  | command3 … ]

Note: | According to requirements, it can be used continuously in one command, and it is usually used in combination with find , grep , wc and other commands.

Example 1: Cooperate with grep to complete the filtering

#过滤出占用端口9092的程序(kafka)
netstat -nalpt | grep 9092

Example 2: Completing statistics with wc

 echo 'yes' | wc -l
 echo 'yes' | wc -m

  

Example 3: Consecutive use of pipes

[root@centOS7 ~]# cat /etc/passwd | grep /bin/bash | wc -l
2
[root@centOS7 ~]# 

  

4. The function of " || " splicing character

Function: Indicates that the next command will be executed after the execution of the previous command fails. Once a successful command is executed, the subsequent commands connected with || will not be executed again.

Syntax format: command1 | | command2   [ | | command3 … ]  

Note: As long as the previous command is executed successfully, the next command will not be executed. 

Note: The command behind  || is a bit of a backstop, similar to try and catch in java.

[root@centOS7 ~]# cat nofile || echo "hi,succ"
cat: nofile: 没有那个文件或目录
hi,succ
[root@centOS7 ~]# cat /etc/hostname || echo "hello succ"
centOS7
[root@centOS7 ~]# 

5. The function of " ; " splicing character

Function: multiple commands are spliced ​​together and then executed, which can reduce the number of (human-computer) interactions.

Syntax format: command1 ; command2   [  ; command3 … ] 

Note: Each command is separated by a  ; , and each command is executed in order from left to right, but it does not care whether it fails or not, and all commands will be executed.

[root@centOS7 ~]# data;echo 'hello';date;cat /etc/hostname
bash: data: 未找到命令...
hello
2022年 10月 17日 星期一 00:34:05 CST
centOS7
[root@centOS7 ~]# 

 

6. The function of " () " splicing symbol 

Function: Execute multiple commands as a whole, while enhancing readability.

Usually, multiple commands are separated by " ; ", and the outermost layer is wrapped with " () ", which is usually used in a slightly more complicated shell.

Syntax format: ( command1 ; command2 ; command3 ; ... )

7. The role of the " > " connector

Function: Redirect normal information (remove error information) to another file

 Note: If you redirect to the same file every time, its effect is to overwrite the original file information, not append content!

#切换到指定目录
cd mypackage && ls
#根据名称查找文件,并把符合条件的名称,重定向输入到tar.txt中
find -name "*.tar.*" > tar.txt
#查看
ls ; cat tar.txt

Note: If you need to append content to the file every time, you need to use >> 

8. The functions and differences of " &> " and " >

> or 1>  Function: Only normal information (non-abnormal information, non-error information) is redirected to the specified file;

2> Function: Only redirect the error information to the specified file;

&> or 2>&1 function: redirect error information and general information to the specified file at the same time.

[root@CentOs7]# lll
-bash: lll: command not found   //由于Linux没有lll这个命令所以会显示错误信息,这个就是stderr输出的错误信息
[root@CentOs7]# lll >test.txt
-bash: lll: command not found  //由于这个是错误信息  所以不能使用标准输出>将信息重定向到test.txt文件中
[root@CentOs7]# lll&>test.txt  //使用&>重定向 ,会一并把错误信息、正确信息,一并重定向到了test.txt文件
[root@CentOs7]# cat test.txt
-bash: lll: command not found  //通过cat命令确实看到了  保存的错误信息 

Note: If you redirect to the same file every time, the effect of the above two commands is to overwrite the original file information, not append content! 

Description: Error and exception information can be output to two different files at the same time.

make xxx 1> normal.txt  2> error.txt

1. In-depth understanding of &> and 2>&1

In short, &> and >& have the same function, they both redirect the standard information + error information to the specified location , they are both shorthand for 2>&1 .

But in the daily development and learning process, it is customary to use &> .

Although they have the same effect, there are still slight differences in usage. It is strongly recommended to use &> directly .

Note: If you prefer to use 2>&1 , it needs to be written after the redirection file, otherwise the effect you want will not be achieved . Example ( note: date is a correct command, data is a deliberately wrong command ):

1) Incorrect usage: (data;echo "hello";date;cat /etc/hosts)  2>&1 >a.txt    #Write in front

2) Correct usage: (data;echo "hello";date;cat /etc/hosts) > b.txt   2>&1 #Write in the back

3) Shorthand example

Note: The &> in shorthand mode can only be placed in front of the file, not in the back, otherwise a syntax error will be prompted!

Nine, linux redirection

9.1. Three streams commonly used in Linux

name   the code  operator Expressed in Java File descriptors under Linux
standard input (stdin)  0 < 或 <<  System.in  /dev/stdin -> /proc/self/fd/0 -> /dev/pts/0
standard output (stdout)  1 >, >>, 1> 或 1>>  System.out /dev/stdout -> /proc/self/fd/1 -> /dev/pts/0
Standard error output (stderr)  2  2> or 2>>   System.err  /dev/stderr -> /proc/self/fd/2 -> /dev/pts/0 

0 is the standard input stdin, usually input from the keyboard

1 is the standard output stdout, usually output to the screen

2 is the standard error output stderr, which is usually output to the screen. After redirecting to the file, the screen will not see it 

9.2 Commonly used redirection symbols

> Redirect normal information to a file / device (the original information of the file will be overwritten)

>> Redirect normal information to a file / device (the original information of the file will not be overwritten, only appended)

&> Redirect normal + abnormal information to a file / device (the original information of the file will be overwritten)

&>>Redirect normal + abnormal information to a file / device (the original information of the file will not be overwritten, only appended)

2> Only output error information to a file / device

There are also some less used ones, which are more brain-intensive. If you are interested in n<&- and >&n and <&-, you can learn about them separately.

Memory tips:

Seeing that there are two angle brackets means that the content is appended, and a single angle bracket means that the previous content will be overwritten! ! !

9.3, /dev/null black hole 

/dev/null is a special device file, any data received by this file will be discarded, commonly known as "black hole"

It is very equivalent to a write-only file, everything written to it is lost forever , and trying to read from it will read nothing, however, /dev/null is very useful for command line and script . 

Use scenarios of black holes:

If you don't want to output the correct / wrong information to the screen, you can output this part of the information into the black hole. 

 1>  /dev/null passes normal information into and out of the black hole

 echo "httpd server is running" >> /dev/null  #如果不希望将信息打印到屏幕,可以输出到黑洞

2>  /dev/null means to output errors to the "black hole" instead of being displayed on the screen.

Summarize

This article comprehensively introduces the differences and functions of common Linux connectors &, &&, ;, |, ||, (), >, &>.

Epilogue

Effectively mastering the use of these connectors can greatly improve your internal strength and take your daily Linux to a higher level.

If you think it's pretty good, and it's not easy to organize, please like and collect it!

notes

Guess you might be interested

1. Download of RHEL7/8, CentOS7/8 | Yum source configuration

2. RHEL7/Centos8 | Configure dynamic/static IP | ping: unknown host www.baidu.com Detailed explanation

3. Temporarily modify the host name | Permanently modify the host name | Detailed explanation

4. View the detailed explanation of the system kernel/operating system version_Check the kernel version_Xuesha Changhong's Blog-CSDN Blog

5. seq command/ mkdir -p batch creation/deletion of folder details

6. In-depth analysis of Linux sort command | sort -k Mm,Nn command detailed explanation

7. Use head tail sed to view the content from the Nth line to the last line | m, n line interval/fixed line | before/after N lines (other than)

8. Enable/disable network card (mixed mode) | set network card queue length/maximum transmission unit | modify/delete eth0 default gateway | set/delete default route | view DNS address according to domain name (network card | IP chapter)

9. Shell script combat | 6 entry-level shell scripts (CPU load, monitoring, scheduled tasks)

10. Shell programming: the difference between /bin/bash and /bin/sh_the difference between /bin/bash /bin/sh

Guess you like

Origin blog.csdn.net/xp871038951/article/details/127355545