我在一本书中遇到以下代码,但仍然不明白为什么。有人可以帮忙解释一下吗?
[root@wd00070319 test]# ls
[root@wd00070319 test]# touch file1
[root@wd00070319 test]# ls
file1
[root@wd00070319 test]# ls > file2
[root@wd00070319 test]# ls
file1 file2
[root@wd00070319 test]# cat file2
file1
file2
[root@wd00070319 test]#
答案 0 :(得分:6)
[root@wd00070319 test]# ls # list the files. (directory is empty!)
[root@wd00070319 test]# touch file1 # create an empty file called "file1"
[root@wd00070319 test]# ls # list the files again (to see "file1")
file1
[root@wd00070319 test]# ls > file2 # list the files, put the result in "file2"
[root@wd00070319 test]# ls # list the files again,
file1 file2
[root@wd00070319 test]# cat file2 # show content of file2
file1
file2 # <-- Note that "file2" is present as well.
[root@wd00070319 test]#
这里的教训可能是ls > file2
之类的命令在实际执行file2
命令之前创建了输出文件(ls
)。
bash参考手册确认了此行为:
3.6重定向
[...] 在执行 命令之前,可以重定向其输入和输出 使用由shell解释的特殊符号。 [...]