20181205 I/O 重定向

I/O 重定向

一.标准输入、标准输出、标准错误
20181205 I/O  重定向
file descriptors (FD,文件描述符 或 Process I/O channels):
进程使用文件描述符来管理打开的文件
[root@tianyun ~]# ls /proc/$$/fd
0 1 2 3 4
0, 1, and 2, known as standard input, standard output, and standard error
20181205 I/O  重定向
二.输出重定向 (覆盖,追加)
正确输出: 1> 1>> 等价于 > >>
错误输出: 2> 2>>
案例 1:输出重定向(覆盖)
[root@tianyun ~]# date 1> date.txt
20181205 I/O  重定向
案例 2:输出重定向(追加)
[root@tianyun ~]# date >> date.txt
20181205 I/O  重定向
案例 3:错误输出重定向
[root@tianyun ~]# ls /home/ /aaaaaaaaa >list.txt
ls: 无法访问/aaaaaaaaa: 没有那个文件或目录
[root@tianyun ~]# ls /home/ /aaaaaaaaa >list.txt 2>error.txt //重定向到不同的位置
20181205 I/O  重定向
案例 4: 正确和错误都输入到相同位置
[root@tianyun ~]# ls /home/ /aaaaaaaaa &>list.txt //混合输出
20181205 I/O  重定向
案例 5: 正确和错误都输入到相同位置
[root@tianyun ~]# ls /home/ /aaaaaaaaa >list.txt 2>&1 //重定向到相同的位置
20181205 I/O  重定向
案例 6:重定向到空设备/dev/null
[root@tianyun ~]# ls /home/ /aaaaaaaaa >list.txt 2>/dev/null //空设备,即将产生的输出丢掉
[root@tianyun ~]# ls /home/ /aaaaaaaaa &>/dev/null //空设备,即将产生的输出丢掉
20181205 I/O  重定向
思考:
cp /etc/passwd /dev/null ???
cp /etc/passwd /etc/passwd1 2>/dev/null ???
案例 7:脚本中使用重定向
[root@tianyun ~]# vim ping1.sh
ping -c1 10.18.40.100
if [ $? -eq 0 ];then
echo "10.18.40.100 is up."
else
echo "10.18.40.100 is down!"
fi
[root@tianyun ~]# vim ping1.sh
[root@tianyun ~]# chmod +x ping1.sh
[root@tianyun ~]# ./ping1.sh
案例 7:脚本中使用重定向
[root@tianyun ~]# vim ping1.sh
ping -c1 10.18.40.100 &>/dev/null
if [ $? -eq 0 ];then
echo "10.18.40.100 is up."
else
echo "10.18.40.100 is down!"
fi
案例 8:脚本中使用重定向
[root@tianyun ~]# vim ping2.sh
ping -c1 10.18.40.100 &>/dev/null
if [ $? -eq 0 ];then
echo "10.18.40.100 is up." >>up.txt
else
echo "10.18.40.100 is down!" >>down.txt
fi
[root@tianyun ~]# vim ping2.sh
[root@tianyun ~]# chmod +x ping1.sh
[root@tianyun ~]# ./ping2.sh

猜你喜欢

转载自blog.51cto.com/8450442/2326730