shell练习题2
需求如下:
写一个shell脚本,检查指定的shell脚本是否有语法错误,若有错误,首先显示错误信息,然后提示用户输入q或Q退出脚本,
输入其他内容则直接用vim打开该shell脚本。
参考解答如下
- 方法1
#!/bin/bash
cmd="/bin/bash"
ed="/usr/bin/vim"
if [ $# -ne 1 ];then
echo "USAGE:$0 script_name"
exit 1
fi
$cmd -n $1
if [ $? -ne 0 ];then
read -p "Please enter Q/q to exit, or other to edit it by vim."
if [ "$REPLY" = "q" -o "$REPLY" = "Q" ];then
exit 0
else
$ed $1
fi
else
echo "The scipt is OK."
fi
- 方法2
#!/bin/bash
cmd="/bin/bash"
ed="/usr/bin/vim"
if [ $# -ne 1 ];then
echo "USAGE:$0 script_name"
exit 1
fi
$cmd -n $1 2>/tmp/err
if [ $? -eq 0 ];then
echo "The script is OK."
else
cat /tmp/err
read -p "Please enter Q/q to exit, or other to edit it by vim." n
if [ -z $n ];then
$ed $1
exit
fi
if [ "$n" = "q" -o "$n" = "Q" ];then
exit
else
$ed $1
exit
fi
fi
注意: bash -n选项只检测语法错误。