文章出處

如果在腳本中重定向許多數據,那么重定向每個echo語句就不太方便了,這種情況下,可以使用exec命令通知shell腳本執行期間重定向特定的文件描述符

文件名為: sh12.sh 

#!/bin/bash
# redirecting all output to a file
exec 1>testout

echo "This is a test of redirecting all output"
echo "from a script to another file."
echo "without haviing to redirect every individual line"

exec命令啟動一個新的shell,并將STDOUT文件描述重定向到一個文件,所有定向到STDOUT的腳本輸出都將重定向到這個文件

運行 sh sh12.sh ,你會發現沒輸出任何東西,然后查看testout文件, cat testout 

輸出:

This is a test of redirecting all output
from a script to another file.
without haviing to redirect every individual line

然后將錯誤信息和正確信息分別重定向不同的文件

文件名 sh13.sh 

#!/bin/bash
# redirecting output to different locations

exec 2>testerror

echo "This is the start of the script"
echo "now reidirecting all output to another location"

exec 1>testout

echo "This output should go to the testout testout file"
echo "but this should go to the testerror file" >&2

運行 sh sh13.sh 

輸出:

This is the start of the script
now reidirecting all output to another location

查看testout文件的內容 cat testout 

輸出: This output should go to the testout testout file 

查看testerror文件的內容 cat testrror 

輸出: but this should go to the testerror file 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()