'>' 輸出到文件中。文件不存在會創建。文件已存在,內容會被覆蓋。文件時間會更新。
第一次輸入'> test', 第二次輸入'> test again', 發現內容
[root@localhost ~]# echo '> test' > echo.log [root@localhost ~]# ll 總用量 8 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg -rw-r--r-- 1 root root 7 2月 1 18:03 echo.log [root@localhost ~]# cat echo.log > test [root@localhost ~]# echo '> test again' > echo.log [root@localhost ~]# cat echo.log > test again [root@localhost ~]# ll 總用量 8 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg -rw-r--r-- 1 root root 13 2月 1 18:04 echo.log
最后輸出只有:'> test again'
刪除echo.log, 測試'>>'
'>>'輸出到文件中。文件不存在會創建。文件已存在,內容會繼續追加在后面。文件時間會更新。
[root@localhost ~]# rm echo.log rm:是否刪除普通文件 "echo.log"?y [root@localhost ~]# ll 總用量 4 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg [root@localhost ~]# echo '> test' >> echo.log [root@localhost ~]# ll 總用量 8 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg -rw-r--r-- 1 root root 7 2月 1 18:11 echo.log [root@localhost ~]# cat echo.log > test [root@localhost ~]# echo '> test again' >> echo.log [root@localhost ~]# ll 總用量 8 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg -rw-r--r-- 1 root root 20 2月 1 18:12 echo.log [root@localhost ~]# cat echo.log > test > test again
最后輸出,文本中有兩行。
> test > test again
輔助記憶:
這兩個都是重定向,
>> 比較長,只有繼續跟在后面附加,文本才會比較長。
> 比較短,理解成替換文本,才不會那么長。
1>> 和 1> 跟 >> 和 > 類似(暫沒發現什么區別),都是標准輸出(stdout)。以下是測試demo。
[root@localhost ~]# echo 'hello' 1>> echo.log [root@localhost ~]# ll 總用量 8 -rw-------. 1 root root 1555 8月 20 15:30 anaconda-ks.cfg -rw-r--r-- 1 root root 6 2月 2 17:02 echo.log [root@localhost ~]# cat echo.log hello [root@localhost ~]# echo 'world' 1>> echo.log [root@localhost ~]# cat echo.log hello world [root@localhost ~]# echo 'world' 1> echo.log [root@localhost ~]# cat echo.log world
2> 和 2>> 這個代表的是標准錯誤輸出(stderr)。
現在用echo肯定看不出結果,因為沒有發生錯誤。
把命令改錯,echo --> echoc, 沒有echoc這個命令的。
[root@localhost ~]# echoc 'hello' 2>> echo.log [root@localhost ~]# cat echo.log -bash: echoc: 未找到命令 [root@localhost ~]# echoc 'hello' 2>> echo.log [root@localhost ~]# cat echo.log -bash: echoc: 未找到命令 -bash: echoc: 未找到命令 [root@localhost ~]# echoc 'hello' 2> echo.log [root@localhost ~]# cat echo.log -bash: echoc: 未找到命令
可以看出2>是內容覆蓋。2>>是錯誤輸出的追加。
還有一個符號是>&, 這是一個整體。>是代表重定向,&符號,我個人把這個理解成類似於java的那種轉義的意思。
2>&1,表示的是把標准錯誤輸出(2表示標准錯誤輸出)定位到標准輸出(1表示標准輸出)。
如果不加&那就是 2>1, 這個表示的含義是錯誤輸出到名字為1的文件中,1在這邊就是表示文件了。所以需要加個&。
例如,這邊有一個rocketmq的啟動命令
nohup mqnamesrv >/usr/local/log/rocketmqlogs/namesrv.log 2>&1 &
nohup和最后的&可以先忽略。跟我們討論關系不大。
mqnamesrv >/usr/local/log/rocketmqlogs/namesrv.log 2>&1這個命令中
>/usr/local/log/rocketmqlogs/namesrv.log表示把命令的輸出定向到/usr/local/log/rocketmqlogs/namesrv.log
2>&1,表示的是把標准錯誤輸出定位到標准輸出。表示錯誤的也定向到/usr/local/log/rocketmqlogs/namesrv.log
但是>/usr/local/log/rocketmqlogs/namesrv.log和2>&1的順序不能反。