4. Linux中的管道和重定向

121 阅读2分钟

本系列都是是基于RedHat体系的,所以CentOS也可以用,但是Debian系列的可能会有些命令上的出入。

1. 管道

1.1 |

管道|:将多条命令组合起来,一次性完成复杂的处理任务。前一个命令的输出作为后一个命令的输入。

- `cut`命令
    - `-d`后跟分割符
    - `-f`后跟切割后第几列

```shell
$ cat /etc/passwd | grep root
root:x:0:0:root:/root:/usr/bin/zsh
$ cat /etc/passwd | grep root | cut -d: -f1
root
$ cat /etc/passwd | grep root | cut -d: -f2
x
$ cat /etc/passwd | grep root | cut -d: -f3
0
```

1.2 tee

|tee管道:管道类似三通,把上游给下游发送的时候,可以进行加工,可以显示在屏幕上,也可以存入文件。

$ ls
$ cat /etc/passwd |tee file888.txt | tail -1
messagebus:x:101:102::/nonexistent:/usr/sbin/nologin
$ ls
file888.txt
$ cat file888.txt 
root:x:0:0:root:/root:/usr/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
...

1.3 xargs

xargs - build and execute command lines from standard input。

参数传递|xargscp rm一些特殊命令不接受其它程序的输入,只接受标准输入,可以使用Xargs来传递参数。

```shell
$ pwd
/root/RemoteWorking
$ touch file{1..5}
$ ls
file1  file2  file3  file4  file5  files
$ cat files
/root/RemoteWorking/file1
/root/RemoteWorking/file3
/root/RemoteWorking/file5
$ cat files | rm -rvf
$ ls
file1  file2  file3  file4  file5  files
$ cat files |xargs rm -rvf
已删除'/root/RemoteWorking/file1'
已删除'/root/RemoteWorking/file3'
已删除'/root/RemoteWorking/file5'
$ ls
file2  file4  files
```
# -i:忽略大小写
# -n:显示行号
# -v:不包含pattern内容
# ^a:行首,以a开始
# ke$:行尾,以ke结尾
$ grep <"pattern"> <filename>	# 在文件中查找,pattern格式*,?,[]

2. 重定向

2.1 输出重定向

bash的set命令可以关闭一些重定向的功能。

  • set -C进制对于已经存在的文件使用<覆盖式的重定向
    • 强制覆盖输出则使用>|
  • set +C关闭上述功能

>:重定向到新的位置,输出重定向,覆盖原有内容

  • 1>:等价于>,相当于写入,会覆盖源文件内容。

  • 1>>:等价于>>,追加

  • 2>:类似1>,是错误输出,只有在执行错误的时候才重定向

  • 2>>:类似1>>,是错误输出,只有在执行错误的时候才重定向

  • &>:同时产生正确输出和错误输出都重定向到同一个文件,然而没什么用,基本都会重定向到/dev/null

    • /dev/null也称为bit bucket,数据黑洞。
    $ ls /home /aaaaaaaaaa &> /dev/null
    $ ls /home /aaaaaaaaaa 1> yes.txt 2> no.txt
    
    # <<EOF和EOF之间的可以取消段落之间的换行符号
    $ cat > 2000.conf <<EOF
    11111
    22222
    33333
    EOF
    

2.2 输入重定向

  • <:从文件中读取,输入重定向

  • <<:Here Document

    $ cat << EOF
    > first line
    > second line
    > EOF
    first line
    second line
    
    $ cat << EOF
    heredoc> first
    heredoc> second
    heredoc> EOF
    first
    second