首先来看看命令执行过程的数据传输情况:
其中stdin(标准输入)0,stdout(标准输出)1,stderr(标准错误)2,称为文件描述符。
在编写脚本时会频繁使用stdin,stdout,stderr,当命令输出文本时,这些输出文本可能
是错误的信息或是正确信息,单靠查看输出文本本身没法区分哪些是正常的,哪些是错误的,
通过文件描述符重定向则可将错误信息和正确信息分别输出到指定文件和设备上。
1.输出重定向stdout > >>
1>:以覆盖的方法将正确的数据输出到指定的文件或设备上;
1>>:以累加的方法将正确的数据输出到指定的文件或设备上;
2>:以覆盖的方法将错误的数据输出到指定的文件或设备上;
2>>:以累加的方法将错误的数据输出到指定的文件或设备上;
注:若文件不存在,系统自动将它建立起来。
(1)将文本追加到目标文件
[root@localhost ~]# echo "hello,world" > temp.txt
[root@localhost ~]# cat temp.txt
hello,world
[root@localhost ~]# echo "a nice day" >> temp.txt
[root@localhost ~]# cat temp.txt
hello,world
a nice day
(2)导出错误信息到目标文件
[root@localhost ~]# ls + 2> temp.txt
[root@localhost ~]# cat temp.txt
ls: 无法访问+: 没有那个文件或目录
将错误的数据丢弃,屏幕上显示正确的信息。
[root@localhost ~]# cmd 2> /dev/null
/dev/null是一个特殊的设备文件,它接收到的任何数据都会被丢弃,称为黑洞。
(3)将stderrt 与stdout分别存到不同文件中
[root@localhost ~]# cmd 2>error.txt 1>out.txt
(4)将stderr与stdout写入同一个文件中。
[root@localhost ~]# cmd 2>&1 output.txt
[root@localhost ~]# cmd >output.txt 2>&1
2.与输出重定向tee结合
tee命令既可以将数据重定向到文件,还可以提供一份重定数据的副本输出到屏幕或是作为后续命令的stdin,
这样就可以将同样的数据继续送到屏幕去处理。
[root@localhost ~]# cat /etc/passwd | tee passwordfile | cut -d ":" -f1
可以将/etc/passwd内容保存一份到passwdfile 文件中,同时将第一列的名字截取下来输出到屏幕上。
tee 默认会将文件覆盖, -a选项可用于追加内容。
stdin 还可以做为命令的参数,只需将-作为命令的文件参数即可
[root@localhost ~]# echo hello world | tee -
hello world
hello world
3.输入重定向stdin < <<
(1)用stdin替代键盘输入以创建新文件
[root@localhost ~]# cat > catfile < /etc/passwd
[root@localhost ~]# ll catfile /etc/passwd
-rw-r--r--. 1 root root 1654 9月 1 13:12 catfile
-rw-r--r--. 1 root root 1654 9月 1 09:28 /etc/passwd
cat > catfile创建一个文件 < /etc/passwd用另一个文件的内容代替键盘输入到创建文件中。
(2)<< 结束输入
[root@localhost ~]# cat > catfile <<eof
> hello
> world
> eof #输入关键字 eof,输入立刻就结束,而不需要ctrl+d结束。
[root@localhost ~]# cat catfile
hello
world
[root@localhost ~]# cat << eof
> hello world
> a nice day
> eof
hello world
a nice day
输入结束字符马上在屏幕上显示出输入的内容
#!/bin/bash
for file_or_folder in 'cat << __EOF__
file1
file2
....
__EOF__'
do
cp -rf $file_or_folder files/
done
总结:在下面一些情况下使用命令输出重定向:
1.屏幕输出信息很重要,而且我们需要将它保存下来时
2.后台执行中的程序,不希望它干扰屏幕正常的输出结果时
3.一些执行命令的已知错误信息,想以“2>/dev/null"将它丢掉时
4.正确信息和错误信息需要分别输出时