前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux中的重定向

Linux中的重定向

原创
作者头像
鱼丸葱面
修改2020-12-23 11:39:27
2.6K0
修改2020-12-23 11:39:27
举报
文章被收录于专栏:ShadowLinuxer

标准输入输出

三种I/O设备

处理数据需要输入输出,在linux中一切皆文件,所操作的输入输出都认为是一个文件,而此文件表现为每打开一个文件系统会分配一个数字,这个数字代表一个文件,这个数字叫文件描述符FileDescriptor

Linux中给程序提供的三种I/O设备

标准输入STDIN 0 默认接受来自终端窗口的输入

标准输出STDOUT 1 默认输出到终端窗口

标准错误STDERR 2 默认输出到终端窗口

每个应用程序都有自己的输入输出错误

代码语言:javascript
复制
查看每个文件都有固定的0输入1输出2错误文件标识符
[root@centos7 ~]# ll /dev/std*
lrwxrwxrwx. 1 root root 15 Dec  3 10:01 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx. 1 root root 15 Dec  3 10:01 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx. 1 root root 15 Dec  3 10:01 /dev/stdout -> /proc/self/fd/1
示例:
通过tail查看文件
[root@centos7 ~]# tail -f anaconda.cfg 
查看文件进程PID
[root@centos7 ~]# ps aux | grep tail
root      76639  0.0  0.0 107992   616 pts/0    S+   21:28   0:00 tail -f anaconda.cfg
root      76649  0.0  0.0 112708   976 pts/1    S+   21:28   0:00 grep --color=auto tail
[root@centos7 fd]# ls /proc/  在/pro目录中可以看到该进程所对应目录
1     29    32     4927  6070   6947   76529   buddyinfo    kallsyms      sched_debug
10    2918  33     4928  6071   7      76534   bus          kcore         schedstat
11    2932  34     4933  6086   71211  76617   cgroups      keys          scsi
113   2935  35     4934  6087   7148   76639   cmdline      key-users     self
[root@centos7 ~]# cd /proc/76639/  进入该进程目录
[root@centos7 76639]# ls   可以查看到目录对应的软链接和fd文件标识符
attr        coredump_filter  gid_map    mountinfo   oom_score      sched      statm
autogroup   cpuset           io         mounts      oom_score_adj  schedstat  status
auxv        cwd              limits     mountstats  pagemap        sessionid  syscall
cgroup      environ          loginuid   net         patch_state    setgroups  task
clear_refs  exe              map_files  ns          personality    smaps      timers
cmdline     fd               maps       numa_maps   projid_map     stack      uid_map
comm        fdinfo           mem        oom_adj     root           stat       wchan
[root@centos7 76639]# ll -i exe 查看exe详细信息为tail程序
162290 lrwxrwxrwx. 1 root root 0 Dec 10 21:28 exe -> /usr/bin/tail
[root@centos7 76639]# cd fd 同时进入fd目录查看详细信息
[root@centos7 fd]# ll -i  此时就可以查看到操作的文件以及固定的文件标识符0输入1输出2错误
total 0
162323 lrwx------. 1 root root 64 Dec 10 21:28 0 -> /dev/pts/0
162324 lrwx------. 1 root root 64 Dec 10 21:28 1 -> /dev/pts/0
166130 lrwx------. 1 root root 64 Dec 10 21:28 2 -> /dev/pts/0
162325 lr-x------. 1 root root 64 Dec 10 21:28 3 -> /root/anaconda.cfg
162326 lr-x------. 1 root root 64 Dec 10 21:28 4 -> anon_inode:inotify            

I/O重定向至文件

默认标准输入的信息输出是到本地窗口,如何将输入信息重定向至其他文件?

如果将输入信息输出至其他文件可以通过重定向方法来实现。

标准输出和错误重定向

标准输出和标准错误可以被重定向到指定文件,而非默认的当前终端

格式:

命令 操作符号 文件名

支持的操作符:

1>或> | 把STDOUT重定向到文件

代码语言:text
复制
[root@centos7 ~]# ifconfig > /data/file0.txt 
[root@centos7 ~]# cat /data/file0.txt 
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.0.101  netmask 255.255.255.0  broadcast 10.0.0.255
        ether 00:0c:29:da:6e:90  txqueuelen 1000  (Ethernet)
        RX packets 66482  bytes 48212751 (45.9 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 43681  bytes 18951628 (18.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

>| 强制覆盖

代码语言:text
复制
[root@centos7 ~]# hostname > /tmp/test1.log
[root@centos7 ~]# cat /tmp/test1.log 
centos7.shadowlinuxer.org
[root@centos7 ~]# ifconfig > /tmp/test1.log 
[root@centos7 ~]# cat /tmp/test1.log 原文件内容已经被覆盖
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.0.101  netmask 255.255.255.0  broadcast 10.0.0.255
        ether 00:0c:29:da:6e:90  txqueuelen 1000  (Ethernet)
        RX packets 64351  bytes 48027614 (45.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 42497  bytes 18830275 (17.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

2> 把STDERR重定向到文件

代码语言:text
复制
[root@centos7 ~]# ls /data/aaa 2> /data/file0.txt 查看不存在的文件目录并重定向
[root@centos7 ~]# cat /data/file0.txt 查看文件内容为ls显示的错误提示内容 
ls: cannot access /data/aaa: No such file or directory

&> 把所有输出重定向到文件

代码语言:text
复制
[root@centos7 ~]# ls /data/ /err &> /data/file1.txt 
[root@centos7 ~]# cat /data/file1.txt 
ls: cannot access /ecc: No such file or directory
/data/:
all
cal.log
data1.txt
dir1
dir1test
dir2
file0.txt

set -C 禁止将内容覆盖已有文件,可以追加

set +C 允许覆盖

追加

>>可以在原有内容基础上对内容进行追加

代码语言:text
复制
[root@centos7 ~]# hostname > /data/file2.txt 
[root@centos7 ~]# cat /data/file2.txt 
centos7.shadowlinuxer.org
[root@centos7 ~]# hostname -I >> /data/file2.txt 
[root@centos7 ~]# cat /data/file2.txt 
centos7.shadowlinuxer.org
10.0.0.101 

把输出和错误重定向追加到文件

代码语言:text
复制
[root@centos7 ~]# hostname > /data/file5.txt 
[root@centos7 ~]# cat /data/file5.txt 
centos7.shadowlinuxer.org
[root@centos7 ~]# ls / /err &>> /data/file5.txt 
[root@centos7 ~]# cat /data/file5.txt 
centos7.shadowlinuxer.org
ls: cannot access /err: No such file or directory
/:
bin
boot
data
dev
etc

多行重定向

使用“<<终止词”命令从键盘把多行重定向给标准输入STDIN,直到终止词位置之前的所有文本都发给标准输入STDIN,有时称为就地文本

代码语言:text
复制
[root@centos7 ~]# systemctl  start postfix  开启邮件服务
[root@centos7 ~]# ss -ntl
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128               *:22                            *:*                  
LISTEN     0      100       127.0.0.1:25                            *:*                  
LISTEN     0      128              :::22                           :::*                  
LISTEN     0      100             ::1:25                           :::*  

使用格式

代码语言:text
复制
mail: illegal option -- -
Usage: mail -eiIUdEFntBDNHRVv~ -T FILE -u USER -h hops -r address -s SUBJECT -a FILE -q FILE -f FILE -A ACCOUNT -b USERS -c USERS -S OPTION users
代码语言:text
复制
[root@centos7 ~]# mail -s test canyon < /data/file0.txt 给canyon用户发邮件
[canyon@centos7 ~]$ mail   canyon用户收到root用户发送的邮件
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/canyon": 1 message 1 new
>N  1 root                  Mon Dec 14 21:59  75/1255  "test"
& 
Message  1:
From root@centos7.shadowlinuxer.org  Mon Dec 14 21:59:08 2020
Return-Path: <root@centos7.shadowlinuxer.org>
X-Original-To: canyon
Delivered-To: canyon@centos7.shadowlinuxer.org
Date: Mon, 14 Dec 2020 21:59:08 +0800
To: canyon@centos7.shadowlinuxer.org
Subject: test
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii
From: root@centos7.shadowlinuxer.org (root)
Status: R

ls: cannot access /data/aaa: No such file or directory
/data/:
all

标准输入重定向

从文件中导入STDIN,代替当前终端的输入设备,使用<来重定向标准输入,某些命令能够接受从文件中导入的STDIN

常见输入类命令bc、rm

代码语言:javascript
复制
[root@centos7 ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
3*3
9

tr命令

转换和删除字符

代码语言:javascript
复制

使用格式:[root@centos7 ~]# tr --help
Usage: tr [OPTION]... SET1 [SET2]
Translate, squeeze, and/or delete characters from standard input,
writing to standard output.

  -c, -C, --complement    取字符集的补集use the complement of SET1
  -d, --delete 删除所有属于第一字符集的字符delete characters in SET1, do not translate
  -s, --squeeze-repeats   把连续重复的字符以一个单独字符标识,即去重
  replace each input sequence of a repeated character
 that is listed in SET1 with a single occurrence of that character
  -t, --truncate-set1   将第一个字符集对应字符转换为第二字符集对应的字符  
  first truncate SET1 to length of SET2
代码语言:text
复制
[root@centos7 ~]#  tr '246' 'ABC'  将246转换为ABC
246
ABC
[root@centos7 ~]# hostname
centos7.shadowlinuxer.org
[root@centos7 ~]# hostname | tr '.' ' '
centos7 shadowlinuxer org
代码语言:text
复制
[root@centos7 ~]# df | tr -s ' '  去重空格
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda2 104806400 1579792 103226608 2% /
devtmpfs 920736 0 920736 0% /dev
tmpfs 931624 0 931624 0% /dev/shm
tmpfs 931624 9788 921836 2% /run
tmpfs 931624 0 931624 0% /sys/fs/cgroup
/dev/sda3 52403200 33120 52370080 1% /data
/dev/sda1 1038336 140300 898036 14% /boot
tmpfs 186328 0 186328 0% /run/user/0
/dev/sr0 57218 57218 0 100% /mnt

管道

管道是用符号“|”标识用来连接多个命令

命令格式:

CMD1 | CMD2 | CMD3 | ....

说明:

  • 将命令1 的输出发送给命令2输入,然后再讲命令2的输出发送至命令3输入
  • 所有命令会在当前shell进程子shell进程中执行
  • 组合多种工具的功能

注意:标准错误不能通过管道转发,需要通过2>&1或者|&来实现

命令格式:

CMD1 2>&1 | CMD2

CMD1 |& CMD2

代码语言:text
复制
[root@centos7 ~]# seq -s+ 1 10 | bc
55

tee命令

利用tee命令可以重定向到多个目标

代码语言:text
复制
[root@centos7 ~]# tee --help
Usage: tee [OPTION]... [FILE]...
Copy standard input to each FILE, and also to standard output.

  -a, --append          追加至文件而不覆盖    append to the given FILEs, do not overwrite
  -i, --ignore-interrupts   ignore interrupt signals

通过tee可以实现:

  • 保存不同阶段的输出
  • 复杂管道的故障排除
  • 同时查看和记录输出
代码语言:text
复制
[root@centos7 ~]# hostname | tee hostname.txt
centos7.shadowlinuxer.org   同时查看和记录输出

[root@centos7 ~]# cat hostname.txt 
centos7.shadowlinuxer.org
[root@centos7 ~]# 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
目录
  • 标准输入输出
    • 三种I/O设备
      • I/O重定向至文件
        • 标准输出和错误重定向
          • 多行重定向
            • 标准输入重定向
              • tr命令
              • 管道
                • tee命令
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档