Shell (一) 脚本错误检测

来源:互联网 发布:macbook如何下载淘宝 编辑:程序博客网 时间:2024/05/02 01:57

1、使用set命令来观察脚本运行情况

源码:

#!/bin/shset -xecho -n "Can you write device drivers? "read answeranswer=`echo $answer | tr [a-z] [A-Z]`#echo $answerif [ "$answer" = Y ]then    echo "Wow, you must be very skilled"else     echo "Neither can I, I'm just an example shell script"fi

运行:

[apache@indigo shell]$ sh example.sh+ echo -n 'Can you write device drivers? 'Can you write device drivers? + read answerY++ echo Y++ tr '[a-z]' '[A-Z]'+ answer=Y+ '[' Y = Y ']'+ echo 'Wow, you must be very skilled'Wow, you must be very skilled[apache@indigo shell]$ sh example.sh+ echo -n 'Can you write device drivers? 'Can you write device drivers? + read answerMM++ echo MM++ tr '[a-z]' '[A-Z]'+ answer=MM+ '[' MM = Y ']'+ echo 'Neither can I, I'\''m just an example shell script'Neither can I, I'm just an example shell script

2、加入可打开和关闭的调试层次

源码:

#!/bin/sh#set -xdebug=$1test $debug -gt 0 && echo "Debug is on"echo -n "Can you write device drivers? "read answertest $debug -gt 0 && echo "The answer is $answer"answer=`echo $answer | tr [a-z] [A-Z]`#echo $answerif [ "$answer" = Y ]then    echo "Wow, you must be very skilled"    test $debug -gt 0 && echo "then:The answer is $answer"else     echo "Neither can I, I'm just an example shell script"    test $debug -gt 0 && echo "else:The answer is $answer"fi
运行:

[apache@indigo shell]$ sh p6.sh 2Debug is onCan you write device drivers? nThe answer is nNeither can I, I'm just an example shell scriptelse:The answer is N

3、检查命令执行结果

shell自动设置内部变量 $? 值为前一个命令执行结果的返回值,命令的返回值是一个已定义的、记录最近执行命令的退出状态的数字。 0为成功,先来看一下它的作用:

[apache@indigo shell]$ command not foundbash: not: command not found[apache@indigo shell]$ echo $?127[apache@indigo shell]$ touch /root/datatouch: cannot touch ‘/root/data’: Permission denied[apache@indigo shell]$ echo $?1[apache@indigo shell]$ cd ..[apache@indigo diary]$ echo $?0[apache@indigo diary]$ 
把这个功能写在函数里,alert.sh:

alert(){  #usage: alert <$?> <object>  if [ "$1" -ne 0 ]  then      echo "WARNING: $2 did not complete successfully." >&2     exit $1  else     echo "INFO: $2 completed successfully" >&2  fi}alert $1 $2

试一下:

[apache@indigo shell]$ commandNotExistbash: commandNotExist: command not found[apache@indigo shell]$ ./alert.sh $? "commandNotExist"WARNING: commandNotExist did not complete successfully.[apache@indigo shell]$ touch /root/datatouch: cannot touch ‘/root/data’: Permission denied[apache@indigo shell]$ ./alert.sh $? "touch /root/data"WARNING: touch did not complete successfully.[apache@indigo shell]$ mkdir data[apache@indigo shell]$ ./alert.sh $? "mkdir data"INFO: mkdir completed successfully


[以上脚本来自<Shell脚本专家指南>]


原创粉丝点击