shell的语法跟c很多不一样,稍有不慎就各种问题,这里有个大神的调试技术总结,我也写了响应的代码验证。
原址:https://www.ibm.com/developerworks/cn/linux/l-cn-shell-debug/
执行以下命令的时候:export DEBUG=true
然后才有调试信息出来,否则就是只有错误提示信息。
调试手段:
- sh -x ./test.sh
- trap "command" signal
- tee /tmp/tmp.txt
- debug函数
- 增强调试:export PS4='+{$LINENO:${FUNCNAME[0]}} '; sh -x ./test.sh;
#! /bin/bash
:<<EOF
info: this is a test shell script
author: oushaojun
date: 2020/03/13
EOF
trap "echo [MY ERROR: line=$LINENO, ret=$?]" ERR
debug()
{
if [ "$DEBUG" = "true" ]
then
$@
fi
}
echo "DEBUG=$DEBUG"
if [ "$DEBUG" = "true" ]
then
echo "shell debug enabled!"
else
echo "shell debug disabled!"
fi
debug echo "input para list(count=$#):"
for i in $@;
do
debug echo $i
done
if [ $1 -a $2 -a $3 ]; then
if [ $1 -gt $2 -o $2 -gt $3 ]; then
debug echo "shell para error!"
else
debug echo "shell para ok"
fi
else
debug echo "shell para not input!"
fi
array=(1 2 3)
debug echo
debug echo "array(${#array[@]}):"
for i in ${array[@]};
do
debug echo $i
done
debug echo "fill new item into array:"
i=0
for file in $(ls ./);
do
debug echo $i:$file"(${#file})"
array[i]=$file
let i=i+1
done
debug echo
debug echo "array new(${#array[@]}):"
for i in ${array[@]};
do
if [ -x $i -a -f $i ]
then
debug echo "normal file excutable: $i"
fi
done
if [ -z $1 -o -z $2 ];then
echo "para 1 or 2 is empty!"
exit 1
else
echo "para1=$1,para2=$2"
fi
var1=$1
var2=$2
if [ $var1 = $var2 ];then
printf "var1 eqaul to var2"
elif [ -z $var1 ];then
printf "var1 is empty"
elif [ -z $var2 ];then
printf "var2 is empty"
else
printf "var1 not equal to var2"
fi
if [ $1 -gt 0 ] 2>>/dev/null ;then
echo "var1 is number"
else
echo "var1 is not number"
fi
echo ""
for i in `seq 1 10`;do
printf "%d " $i
done
echo
for((i=0;i<10;i++));do
printf "%d " $i
done
temp=0
while true;do
read -p "input number:(bigger than 10 to break)" temp
echo $temp
case $temp in
10)
echo "break out"
break
;;
*)
echo "continue"
;;
esac
done
echo "wc:"
wc -l <<EOF
test1
test2
test3
EOF
abc