【小知识】Linux中&&、&、|、||等特殊符号

Administrator 401 2022-07-19

Linux中&&、&、|、||等特殊符号

&& 和 &

“ & ” 表示任务后台执行,与nohup命令功能差不多。

# 运行jar包,并且置于后台执行,执行的日志重定向到当前默认的log.txt文件中
[root@localhost local]$ java -jar test.jar > log.txt &

“ && ” 表示前一条命令执行成功时,才执行后一条命令。

# 执行ls -l成功后,执行cd ..
[root@localhost tmp]$ ls -l && cd .. 
总用量 4 
-rw-r–r–. 1 root root 2252 1月   4 22:25 log.txt 
-rw——-. 1 root root    0 1月   3 23:23 yum.log 
[root@localhost /]$

| 和 ||

“ | ” 表示管道,上一条命令的输出,作为下一条命令参数(输入)。

# 查询全部进程后输出结果在进行过滤跟 进行中包含aux的进程。
[root@localhost ~]$ ps -aux | grep aux 
Warning: bad syntax, perhaps a bogus ‘-‘? See /usr/share/doc/procps-3.2.8/FAQ 
root        53  0.0  0.0      0     0 ?        S    16:33   0:00 [ata_aux] 
root      2379  4.0  0.1 110224  1172 pts/2    R+   22:55   0:00 ps -aux 
root      2380  0.0  0.0 103316   868 pts/2    D+   22:55   0:00 grep aux 

“ || ” 表示上一条命令执行失败后,才执行下一条命令。

[root@localhost tmp]$ als -l || cd ..
-bash: als: command not found
[root@localhost /]$ 

> 和 >>

“ > ” 表示stdout标准输出信息重定向输出,覆盖写。

[root@localhost ~]$ cat test.txt
Hello
[root@localhost ~]$ echo 'World' > test.txt
[root@localhost ~]$ cat test.txt
World

“ >> ”表示内容追加写。

[root@localhost ~]$ cat test.txt
Hello
[root@localhost ~]$ echo 'World' >> test.txt
[root@localhost ~]$ cat test.txt
HelloWorld

&> 、2>&1 和 2>1

“ &> ” 表示stdout标准输出和stderr错误输出信息,重定向输出,覆盖写。

[root@localhost ~]$ cat test.txt
World
[root@localhost ~]$ lll
-bash: lll: command not found 
[root@localhost ~]$ lll > test.txt
[root@localhost ~]$ cat test.txt
# 由于这个是错误信息,所以不能使用标准输出>将信息重定向到test文件中,但覆盖写为空
# 所以错误信息直接在控制台打印出来了
[root@localhost ~]$ lll &> test.txt
[root@localhost ~]$ cat test.txt
-bash: lll: command not found
# 使用&>重定向错误信息没有输出到控制台了,表示错误信息正确重定向到了test文件,也同样是覆盖写

“ 2>&1 ” 表示把标准错误的输出重定向到标准输出1,&指示不要把1当做普通文件,而是fd=1即标准输出处理。

“ 2>1 ” 表示把标准错误的输出重定向到1,但这个1不是标准输出,而是一个名为1的文件。

linux重定向的设备代码

空设备文件/dev/null
标准输入(stdin) 代码为0,实际映射关系:/dev/stdin -> /proc/self/fd/0
标准输出(stdout)代码为1,实际映射关系:/dev/stdout -> /proc/self/fd/1
标准错误输出(stderr)代码为2,实际映射关系:/dev/stderr ->/pro/self/fd/2

command>a 2>1 、command>a 2>a 与 command>a 2>&1的区别

  1. command>a 2>&1 等价于 command 1>a 2>&1
    意思为执行command产生的标准输入重定向到文件a中,标准错误也重定向到文件a中。

  2. command>a 2>a 不等价于 command 1>a 2>&1,其区别如下:
    i. command>a 2>a打开文件两次,而command 1>a 2>&1只打开文件一次;
    ii. command>a 2>a由于打开文件两次,导致stdout被stderr覆盖;
    iii. 从IO效率上来讲,command 1>a 2>&1比command 1>a 2>a的效率更高。

  3. command>a 2>1 等价于 command 1>a 2>1
    意思为执行command产生的标准输入重定向到文件a中,标准错误重定向到文件1中。

    ————————————————
    版权声明:本文为CSDN博主「小学僧来啦」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/bocai8058/article/details/82932397