1.I/O重定向符
I/O重定向符如下:
- cmd1 | cmd2:管道,接收cmd1的标准输出作为cmd2的标准输入。
- >file:将标准输出定向到file
- <file:从file接收标准输入
- >>file:将标准输出定向到file,如果file存在则附加在后面
- >|file:即使设置了noclobber仍然强制标准输出到file。
shell提供了一种称为noclobber的特性,该特性可防止重定向时不经意地重写了已存在的文件。通过设置变量noclobber可以
将此特 性打开。打开后若将输出重定向到某个已存在文件,则shell将报告错误消息,并且不执行重定向命令。
例如:
root@-virtual-machine:~# cat a.txt
123
root@virtual-machine:~# set -o | grep "noclobber"
noclobber off
root@virtual-machine:~# echo "test1" > a.txt
root@virtual-machine:~# cat a.txt
test1
root@virtual-machine:~# set -o noclobber
root@virtual-machine:~# set -o | grep "noclobber"
noclobber on
root@gmdz-virtual-machine:~# echo "hello" > a.txt
-bash: a.txt: 无法覆盖已存在的文件
root@virtual-machine:~# echo "hello" >| a.txt
root@virtual-machine:~# cat a.txt
hello
- n>|file:即使设置了noclobber仍强制从文件描述符n中输出到file。
例如:
root@-virtual-machine:~# cat a.txt
123
root@virtual-machine:~# set -o | grep "noclobber"
noclobber off
root@virtual-machine:~# ls nosuchfile 2> a.txt
root@virtual-machine:~# cat a.txt
ls: 无法访问nosuchfile: 没有那个文件或目录
root@virtual-machine:~# echo "123" > a.txt
root@virtual-machine:~# cat a.txt
123
root@virtual-machine:~# set -o noclobber
root@virtual-machine:~# set -o | grep "noclobber"
noclobber on
root@virtual-machine:~# ls nosuchfile 2> a.txt
-bash: a.txt: 无法覆盖已存在的文件
root@virtual-machine:~# cat a.txt
123
root@virtual-machine:~# ls nosuchfile 2>| a.txt
root@virtual-machine:~# cat a.txt
ls: 无法访问nosuchfile: 没有那个文件或目录
- <>file:使用file同时作为输入和输出。
- n<>file,以读写方式打开file,并将n重定向到该文件。
要说明这个重定向符之前,先要说明exec命令:
shell的内建命令exec将并不启动新的shell,而是用要被执行命令替换当前的shell进程,并且将老进程的环境清理掉,而且exec命令
后的其它命令将不再执行。因此,