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放弃并退出;
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