通常是用文件或命令的執行結果來代替鍵盤作為新的輸入設備,而新的輸出設備通常指的就是文件。
| 命令符號格式 | 作用 |
|---|---|
| 命令 < 文件 | 將指定文件作為命令的輸入設備 |
| 命令 << 分界符 | 表示從標準輸入設備(鍵盤)中讀入,直到遇到分界符才停止(讀入的數據不包括分界符),這里的分界符其實就是自定義的字符串 |
| 命令 < 文件 1 > 文件 2 | 將文件 1 作為命令的輸入設備,該命令的執行結果輸出到文件 2 中。 |
[root@localhost ~]# cat /etc/passwd
#這里省略輸出信息,讀者可自行查看
[root@localhost ~]# cat < /etc/passwd
#輸出結果同上面命令相同
[root@localhost ~]# cat << 0
>c.biancheng.net
>Linux
>0
c.biancheng.net
Linux
[root@localhost ~]# cat a.txt
[root@localhost ~]# cat < /etc/passwd > a.txt
[root@localhost ~]# cat a.txt
#輸出了和 /etc/passwd 文件內容相同的數據
[root@localhost ~]# touch demo1.txt
[root@localhost ~]# ls -l demo1.txt
-rw-rw-r--. 1 root root 0 Oct 12 15:02 demo1.txt
[root@localhost ~]# ls -l demo2.txt <-- 不存在的文件
ls: cannot access demo2.txt: No such file or directory
在此基礎上,標準輸出重定向和錯誤輸出重定向又分別包含清空寫入和追加寫入兩種模式。因此,對于輸出重定向來說,其需要用到的符號以及作用如表 2 所示。再次強調,要想把原本輸出到屏幕上的數據轉而寫入到文件中,這兩種輸出信息就要區別對待。
| 命令符號格式 | 作用 |
|---|---|
| 命令 > 文件 | 將命令執行的標準輸出結果重定向輸出到指定的文件中,如果該文件已包含數據,會清空原有數據,再寫入新數據。 |
| 命令 2> 文件 | 將命令執行的錯誤輸出結果重定向到指定的文件中,如果該文件中已包含數據,會清空原有數據,再寫入新數據。 |
| 命令 >> 文件 | 將命令執行的標準輸出結果重定向輸出到指定的文件中,如果該文件已包含數據,新數據將寫入到原有內容的后面。 |
| 命令 2>> 文件 | 將命令執行的錯誤輸出結果重定向到指定的文件中,如果該文件中已包含數據,新數據將寫入到原有內容的后面。 |
| 命令 >> 文件 2>&1 或者 命令 &>> 文件 | 將標準輸出或者錯誤輸出寫入到指定文件,如果該文件中已包含數據,新數據將寫入到原有內容的后面。注意,第一種格式中,最后的 2>&1 是一體的,可以認為是固定寫法。 |
[root@localhost ~]# cat Linux.txt > demo.txt
[root@localhost ~]# cat demo.txt
Linux
[root@localhost ~]# cat Linux.txt > demo.txt
[root@localhost ~]# cat demo.txt
Linux <--這里的 Linux 是清空原有的 Linux 之后,寫入的新的 Linux
[root@localhost ~]# cat Linux.txt >> demo.txt
[root@localhost ~]# cat demo.txt
Linux
Linux <--以追加的方式,新數據寫入到原有數據之后
[root@localhost ~]# cat b.txt > demo.txt
cat: b.txt: No such file or directory <-- 錯誤輸出信息依然輸出到了顯示器中
[root@localhost ~]# cat b.txt 2> demo.txt
[root@localhost ~]# cat demo.txt
cat: b.txt: No such file or directory <--清空文件,再將錯誤輸出信息寫入到該文件中
[root@localhost ~]# cat b.txt 2>> demo.txt
[root@localhost ~]# cat demo.txt
cat: b.txt: No such file or directory
cat: b.txt: No such file or directory <--追加寫入錯誤輸出信息
新聞熱點
疑難解答