Linux 输入重定向和输出重定向

2020-11-20  本文已影响0人  月饮沙

输入重定向

使用输入重定向 <,<<

示例

# 创建一个空文件
[root@localhost ~]# touch hosts
[root@localhost ~]# cat hosts
# << 将两个EOF之间的内容作为输入,重定向到file中。
# EOF可以更改为任意符号,只要开头和结尾一致即可
[root@localhost ~]# cat > file <<EOF
> y
> 
> 
> EOF
[root@localhost ~]# cat file 
y


# < 将file中的y作为输入
[root@localhost ~]# cp /etc/hosts hosts <file 
cp: overwrite ‘hosts’? 
[root@localhost ~]# cat hosts 
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

输出重定向

输出重定向 >,>>,1>,2>,&>,1>>,2>>,&>>

示例

# 创建一个新文件
[root@localhost ~]# touch test
[root@localhost ~]# cat test
# 初始文件为空,添加一行内容
[root@localhost ~]# echo 12345 > test
[root@localhost ~]# cat test
12345
# > 覆盖文件
[root@localhost ~]# echo 23445 >test
[root@localhost ~]# cat test
23445
# >>在文件末尾追加
[root@localhost ~]# echo 1234 >>test
[root@localhost ~]# cat test
23445
1234

# 消息重定向
echo "ls && cp host test" > test.sh
# 默认错误消息会输出到屏幕上,正确的消息重定向到文件中
[root@localhost ~]# sh test.sh > test
cp: cannot stat ‘host’: No such file or directory
[root@localhost ~]# cat test
anaconda-ks.cfg
file
hosts
original-ks.cfg
test
test.sh
# 1 将正确的消息重定向到文件中
[root@localhost ~]# sh test.sh 1> test
cp: cannot stat ‘host’: No such file or directory
[root@localhost ~]# cat test
anaconda-ks.cfg
file
hosts
original-ks.cfg
test
test.sh
# 2 将错误的消息重定向到文件中
[root@localhost ~]# sh test.sh 2> test
anaconda-ks.cfg  file  hosts  original-ks.cfg  test  test.sh
[root@localhost ~]# cat test
cp: cannot stat ‘host’: No such file or directory
# & 将正确的和错误的消息都重定向到文件中
[root@localhost ~]# sh test.sh &> test
[root@localhost ~]# cat test
anaconda-ks.cfg
file
hosts
original-ks.cfg
test
test.sh
cp: cannot stat ‘host’: No such file or directory
上一篇 下一篇

猜你喜欢

热点阅读