数据流重定向

经常用到的2个重定向

$ echo 'hello shiyanlou' > redirect
$ echo 'www.shiyanlou.com' >> redirect

Linux 默认提供了三个特殊设备,用于终端的显示和输出,分别为stdin(标准输入,对应于你在终端的输入),stdout(标准输出,对应于终端的输出),stderr(标准错误输出,对应于终端的输出)。

文件描述符 设备文件 说明
0 /dev/stdin 标准输入
1 /dev/stdout 标准输出
2 /dev/stderr 标准错误
文件描述符:文件描述符在形式上是一个非负整数。实际上,它是一个索引值,指向内核为每一个进程所维护的该进程打开文件的记录表。当程序打开一个现有文件或者创建一个新文件时,内核向进程返回一个文件描述符。在程序设计中,一些涉及底层的程序编写往往会围绕着文件描述符展开。但是文件描述符这一概念往往只适用于 UNIX、Linux 这样的操作系统。

 

# 将标准错误重定向到标准输出,再将标准输出重定向到文件,注意要将重定向到文件写到前面
$ cat Documents/test.c hello.c >somefile 2>&1
# 或者只用bash提供的特殊的重定向符号"&"将标准错误和标准输出同时重定向到文件
$ cat Documents/test.c hello.c &>somefilehell

 

tee 

除了需要将输出重定向到文件,也需要将信息打印在终端

 

永久重定向

# 先开启一个子 Shell
$ zsh
# 使用exec替换当前进程的重定向,将标准输出重定向到一个文件
$ exec 1>somefile
# 后面你执行的命令的输出都将被重定向到文件中,直到你退出当前子shell,或取消exec的重定向(后面将告诉你怎么做)
$ ls
$ exit
$ cat somefile

 

 

 xargs 命令

cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z

    cat test.txt | xargs

a b c d e f g h i j k l m n o p q r s t u v w x y z
cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z

echo "nameXnameXnameXname" | xargs -dX name name name name
echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name

与find 结合使用
find . -type f -name "*.log" -print0 | xargs -0 rm -f
find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz

 




posted @ 2018-07-31 14:55  myself_think  阅读(158)  评论(0)    收藏  举报