BASH第八课作业

1写一个脚本,完成如下功能(使用函数):
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

exec 2>> /dev/null

while getopts :D:A: opt; do
    case $opt in
        D)
        DES="$OPTARG"
        ;;
        A)
        AUT="$OPTARG"
        ;;
        ?)
         echo "Invalid param" ;;
    esac
done

dir=/tmp/tkp
if [ ! -d $dir ];then
	mkdir $dir
fi

NUMBER=$#
declare -a args
i=1
while [ $i -le $NUMBER ]
do
        args[$i]=$1                         
        #echo ${args[$i]}
        ((i++))                       
        shift                    
done
file=${args[$NUMBER]}


file_path=$dir/$file
function touch_file()
{
		touch $file_path
		echo "#!/bin/bash" >> $file_path 
		echo "# Description: $DES" >> $file_path
		echo "# Author: $AUT" >> $file_path
		echo "#" >> $file_path
}
function syntax_file()
{
	bash -n $file_path
	if [ $? -eq 0 ];then
		chmod 755 $file_path
		echo "script is correct,you can run it now"
	else
		echo "the file has syntax error"
		read -p "Y/N,Y to continue edit the script,N to ignore the error and exit" flag
		if [ $flag == "Y" -o $flag == "y" ];then
			vim + $file_path
			sync_file
		elif [ $flag == "N" -o $flag == "n" ];then
			echo "quit script"
			exit 2
		else
			echo "Invalid parameter,quit script"
			exit 1
		fi
	fi
}
if [ -f $file_path ];then
	head -1 $file_path | grep "^\#\!\/bin\/bash$" >> /dev/null
	if [ $? -ne 0 ];then
		echo "Syntax error!!!"
		exit 1
	else
		vi + $file_path
		syntax_file
		
	fi
elif [ ! -f $file_path ];then
	touch_file
fi


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值