bash编程之 第六课作业

1、脚本使用格式:

mkscript.sh [-D|--description "script description"] [-A|--author "script author"]  文件名

2、如果文件事先不存在,则创建;且前几行内容如下所示:

#!/bin/bash

# Description: script description

# Author: script author

#

3、如果文件事先存在,但不空,且第一行不是“#!/bin/bash”,则提示语法错误并退出;如果第一行是“#!/bin/bash”,则使用vim打开脚本;把光标直接定位至最后一行

4、打开脚本后关闭时判断脚本是否有语法错误如果有,提示输入y继续编辑,输入n放弃并退出;如果没有,则给此文件以执行权限;

#!/bin/bash
#

a1=$1
a2=$2
a3=$3
a4=$4
a5=$5

desc=""
if [ $1 == "-D" -o $1 == "--description" ];then
        desc=$2
elif [ $3 == "-D" -o $3 == "--description" ];then
        desc=$4
fi
if [ $# -eq 1 ];then
        filename=$1
elif [ $# -eq 3 ];then
        filename=$3
elif [ $# -eq 5 ];then
        filename=$5
else
        echo 'please use format: mkscript.sh [-D|--description "script description"] [-A|--author "script author"] filename'
        exit 1
fi

echo "desc=$desc"
echo "author=$author"
echo "filename=$filename"

if ! [ -f $filename ]; then
        touch $filename
        echo "#!/bin/bash" >> $filename
        echo "# Description: $desc" >> $filename
        echo "# Author: $author" >> $filename
        echo "#" >> $filename
elif [ -s $filename ]; then
        str=`grep -n "^#\!/bin/bash$" $filename`
        str2=${str%:*}             #find the line_number of #\!/bin/bash
        if [ $str2 -ne 1 ]; then
                echo "the first line of $filename is not #\!/bin/bash"
                exit 2
        else
                vi + $filename                
                trap "myquit" 1 2 3 15
        fi
fi


myquit(){
        bash -n $filename &> /dev/null
        if [ $? -eq 0 ]; then
                chmod +x $filename
        else
                read -p 'there is something wrong, continue to edit ? y/n : ' yesOrNo
                if [ $yesOrNo == "n" ]; then
                        exit 0
                fi
        fi
}

猜你喜欢

转载自oracle-api.iteye.com/blog/2365709