shell 编程 (8)重定向

25 篇文章 0 订阅
15 篇文章 0 订阅

cmd > file: 输出重定向到文件

cmd < file: 输入重定向到文件

cmd >> file: 输出追加重定向到文件

n > file: 将文件描述符为n 的文件重定向到file

n >> file: 描述符为n的文件追加重定向到file

n >$ m: 输出文件m和n合并到m

n <$ m: 输入文件m 合并 到n

<< tag: 开始标记tag和结束标记tag之间的内容作为输入

文件描述符:

STDIN: 0

STDOUT: 1

STDERR: 2

一般情况下,每个unix/linux命令运行时会打开3个文件:stdin, stdout, stderr.

cmd > file: stdout重定向到file,cmd < file: stdin重定向到file, cmd 2 > file: stderr 重定向到file,

cmd > file 2 >&1: stdout与stderr合并重定向到file,

cmd < file1 > file2: stdin重定向到file1, stdout重定向到file2

 

eg:

1. 输出重定向

[root@k8s-master test3]# who > users
[root@k8s-master test3]# cat users
root     tty1         2020-03-21 00:04
root     pts/0        2020-03-21 00:05 (192.168.159.1)
[root@k8s-master test3]# who
root     tty1         2020-03-21 00:04
root     pts/0        2020-03-21 00:05 (192.168.159.1)
[root@k8s-master test3]# 

2. 输入重定向

[root@k8s-master test3]# wc -l ./t2.sh 
5 ./t2.sh
[root@k8s-master test3]# wc -l < ./t2.sh 
5
[root@k8s-master test3]# 

[root@k8s-master test3]# wc -l ./t2.sh  > wc-t2.txt
[root@k8s-master test3]# cat wc-t2.txt 
5 ./t2.sh
[root@k8s-master test3]# 

3. Here Document

cmd << delimiter

document

delimiter

两个delimeter之间的内容重定向给stdin。

最后的delimiter必须顶格,前后不能有任何其他字符,空格也不可以。

[root@k8s-master test3]# wc -l <<EOF
> HELLO
> WORLD
> EOF
2
[root@k8s-master test3]# 

4. 屏蔽输出

/dev/null中写入的内容全部会被丢弃,读取不到任何内容。

cmd > /dev/null 2>&1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值