在上一篇关于shell编程的例子中,有讲到把shell脚本进行扩展之后重定向到一个文件中,以便进行查看和调试https://www.jb51.net/article/62435.htm。但是,若是有另一种情况:只是在某些地方进行重定向,而其他地方不进行重定向。那么我们就来修改一下上一篇中的例子来进行这种需求的满足:
#!/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