在上一篇關(guān)于shell編程的例子中,有講到把shell腳本進(jìn)行擴(kuò)展之后重定向到一個(gè)文件中,以便進(jìn)行查看和調(diào)試https://www.jb51.net/article/62435.htm。但是,若是有另一種情況:只是在某些地方進(jìn)行重定向,而其他地方不進(jìn)行重定向。那么我們就來(lái)修改一下上一篇中的例子來(lái)進(jìn)行這種需求的滿(mǎn)足:
#!/bin/bash
function setlogfile
{
if ! [ -z "$1" ]; then
echo "logfilename is not empty!" >> kthh
exec 3>1
exec 4>2
exec 2>> $1
exec 1>> $1
fi
}
num1=$1
logfile=$2
execlogfile=$3
setlogfile ${execlogfile}
set -x
if [ $num1 -eq 0 ]; then
echo "num1 is 0">> ${logfile}
elif [ $num1 -ge 0 ]; then
echo "num1 is grate 0">> ${logfile}
else
echo "num1 is less 0">> ${logfile}
fi
exec 2>4
exec 1>3
if [ $num1 -eq 0 ]; then
echo "num1 is 0 again">> ${logfile}
fi
[root@UFO shellprogram]# ./testexecutelog.sh 0 msglog execlog
+ exec
+ '[' 0 -eq 0 ']'
+ echo 'num1 is 0 again'
[root@UFO shellprogram]# cat execlog
+ '[' 0 -eq 0 ']'
+ echo 'num1 is 0'
+ exec