接著上節(jié)課的標(biāo)準(zhǔn)輸出講。
視頻最后我們通過重定向把標(biāo)準(zhǔn)輸出寫到了文件中,但是錯(cuò)誤輸出還是留在了屏幕上。
root@turbo:~# ls test test.c root@turbo:~# root@turbo:~# ./test xxxxxx 錯(cuò)誤輸出 ------ 標(biāo)準(zhǔn)輸出 root@turbo:~# root@turbo:~# ./test > out.log xxxxxx 錯(cuò)誤輸出 root@turbo:~# root@turbo:~#有沒有什么方法把錯(cuò)誤輸出也寫到文件里面?
重定向分為輸入重定向和輸出重定向,輸入重定向使用場(chǎng)景比較少,我們主要來講講輸出重定向。
先把程序修改一下,只留下標(biāo)準(zhǔn)輸出。
#include運(yùn)行程序的時(shí)候會(huì)在屏幕上打印字符串,如果希望把這些字符串收集起來,運(yùn)行的時(shí)候加上輸出符號(hào)和文件名,字符串就寫到了文件里面。int main() { //fprintf(stderr, "xxxxxx 錯(cuò)誤輸出 "); fprintf(stdout, "------ 標(biāo)準(zhǔn)輸出 "); return 0; }
root@turbo:~# gcc test.c -o test root@turbo:~# ./test > out.log root@turbo:~#一個(gè)符號(hào)表示清空文件重新寫入,兩個(gè)符號(hào)表示往文件的后面追加。
再把程序改回來,這次既有標(biāo)準(zhǔn)輸出,也有錯(cuò)誤輸出:
#include代碼的運(yùn)行現(xiàn)象是這樣的:int main() { fprintf(stderr, "xxxxxx 錯(cuò)誤輸出 "); fprintf(stdout, "------ 標(biāo)準(zhǔn)輸出 "); return 0; }
root@turbo:~# ls test test.c root@turbo:~# ./test xxxxxx 錯(cuò)誤輸出 ------ 標(biāo)準(zhǔn)輸出 root@turbo:~#如果像剛才一樣加上重定向,那只能把標(biāo)準(zhǔn)輸出寫到文件中:
root@turbo:~# ls test test.c root@turbo:~# ./test > out.log xxxxxx 錯(cuò)誤輸出 root@turbo:~# root@turbo:~#其實(shí)這種寫法也等價(jià)于這樣的:
root@turbo:~# ls test test.c root@turbo:~# ./test 1> out.log xxxxxx 錯(cuò)誤輸出 root@turbo:~# root@turbo:~#0 1 2在 Linux 中分別表示標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯(cuò)誤處理,大部分時(shí)候我們會(huì)把1省略掉。
如果想把錯(cuò)誤信息也收集到文件中,可以這樣寫:
root@turbo:~# ls out.log test test.c root@turbo:~# ./test 1> out.log 2> error.log root@turbo:~#意思也很明確,標(biāo)準(zhǔn)輸出寫到文件out.log中,錯(cuò)誤輸出寫到文件error.log中。
這就是上節(jié)課說的,stdout和stderr可以把不同級(jí)別的信息分開。
如果想把標(biāo)準(zhǔn)輸出和錯(cuò)誤輸出寫到同一個(gè)文件中,可以使用這條命令:
root@turbo:~# ./test > out.log 2>&1 root@turbo:~#
2>&1這個(gè)符號(hào)的意思就是把錯(cuò)誤輸出重定向到標(biāo)準(zhǔn)輸出。
需要注意的是,此處的順序不能修改,否則達(dá)不到想要的效果。
有的時(shí)候我們不想看到輸出信息,也不想保存輸出信息,可以考慮dev下的null設(shè)備文件,所有寫進(jìn)去的數(shù)據(jù)都會(huì)被丟棄。
root@turbo:~# ./test > /dev/null 2>&1 root@turbo:~#
審核編輯:劉清
-
Linux
+關(guān)注
關(guān)注
87文章
11511瀏覽量
213880 -
字符串
+關(guān)注
關(guān)注
1文章
590瀏覽量
22308
原文標(biāo)題:2分鐘搞懂輸出重定向
文章出處:【微信號(hào):學(xué)益得智能硬件,微信公眾號(hào):學(xué)益得智能硬件】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
linux shell數(shù)據(jù)重定向(輸入重定向與輸出重定向)詳細(xì)分析
Linux Shell系列教程之(十六) Shell輸入輸出重定向
五分鐘搞懂PID控制算法
實(shí)現(xiàn)printf函數(shù)的重定向
重定向printf輸出到串口輸出的方法
DNS 重定向的缺陷
管道符、重定向與環(huán)境變量
Keil下使用STlink重定向printf的配置

Linux I/O重定向詳解
printf輸出重定向的方法

評(píng)論