linux shell基本語法和調試技術

shell的語法跟c很多不一樣,稍有不慎就各種問題,這裏有個大神的調試技術總結,我也寫了響應的代碼驗證。

 

原址:https://www.ibm.com/developerworks/cn/linux/l-cn-shell-debug/

執行以下命令的時候:export DEBUG=true

然後纔有調試信息出來,否則就是隻有錯誤提示信息。

調試手段:

  1. sh -x ./test.sh
  2. trap "command" signal
  3. tee /tmp/tmp.txt
  4. debug函數
  5. 增強調試: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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章