计算机网络/计算机科学与应用/系统/运维/开发

Shell脚本编程 - 输入与输出重定向

1>或1>>可以将标准输出信息重定向到文件(1可以忽略不写,默认值就是1)

2>或2>>将错误的输出信息重定向到文件


标准输出的文件描述符为1

标准错误输出的文件描述符为2

标准输入的文件描述符则为0


> 或 >> 将输出信息重定向到文件

1> 或 1>> 将标准输出信息重定向到文件


2> 将错误输出信息重定向到文件 如果文件不存在 则自动创建 如果已存在 则覆盖原先文件内容

2>> 将输出信息重定向到文件  如果文件不存在 则系统会自动创建  如果已存在  则将输出信息追加到该文件原有信息末尾


[root@VM-4-2-centos shell]# echo "hello the world" >text.txt
[root@VM-4-2-centos shell]# cat text.txt 
hello the world


覆盖重定向  原先数据丢失

[root@VM-4-2-centos shell]# echo "Jacob Shell Script" >text.txt
[root@VM-4-2-centos shell]# cat text.txt 
Jacob Shell Script


>> 追加数据,原数据不丢失

[root@VM-4-2-centos shell]# echo "test file" >> text.txt 
[root@VM-4-2-centos shell]# cat text.txt 
Jacob Shell Script
test file


2> 会覆盖原先内容

[root@VM-4-2-centos shell]# ls /nofiles 2> text.txt
[root@VM-4-2-centos shell]# cat text.txt 
ls: cannot access /nofiles: No such file or directory

2>> 追加内容 不覆盖数据

[root@VM-4-2-centos shell]# ls /nofiles 2>> text.txt
[root@VM-4-2-centos shell]# cat text.txt 
ls: cannot access /nofiles: No such file or directory
ls: cannot access /nofiles: No such file or directory


将标准输出和错误输出分别重定向到不同文件:

[root@VM-4-2-centos shell]# ls -l /etc/hosts /nofile > ok.txt 2> error.txt
[root@VM-4-2-centos shell]# cat ok.txt 
-rw-r--r-- 1 root root 234 Jul 20 11:50 /etc/hosts
[root@VM-4-2-centos shell]# cat error.txt 
ls: cannot access /nofile: No such file or directory

使用&>符号可以同时将标准输出和错误输出都重定向到一个文件(覆盖

使用&>>符号实现追加重定向


可以使用2>&1将错误输出重定向到标准正确输出

可以使用1>&2将标准正确输出重定向到错误输出


微信小程序 https://www.javascriptcn.com/interview-weixinapp/677f48463d78df11d950b260.html

评论

^