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放弃并退出;
如果没有,则给此文件以执行权限;

mkscript.sh文件代码如下:

 1 #!/bin/bash
 2 #
 3 echo $1 > a
 4 #echo "1: $1"
 5 #echo "2: $2"
 6 #echo "Count for args is: $#"
 7 
 8 #文件不存在
 9 if [ ! -f "$2" ]; then
10     touch "$2"
11     echo "#!/bin/bash" >> $2
12     description=`sed 's/[|]|"//g' aa |awk '{print $1}' | awk -F-- '{print $2}'`
13     #echo $description  
14     #description
15     #echo ${#description}
16     #把description中的首字母大写
17     #echo ${description:0:1}
18     first_up_1=`echo ${description:0:1} | tr '[a-z]' '[A-Z]'`
19     echo "#$first_up_1${description:1:${#description}}:":`sed 's/[|]|"//g' aa |awk '{print $2,$3}'` >> $2
20     
21     author=`sed 's/[|]|"//g' aa |awk '{print $4}' | awk -F-- '{print $2}'`
22     #echo $author 
23     #计算author的长度
24     #echo ${#author}
25     #把author中的首字母大写
26     #echo ${author:0:1}
27     first_up_2=`echo ${author:0:1} | tr '[a-z]' '[A-Z]'`  
28     echo "#$first_up_2${author:1:${#author}}:"`sed 's/[|]|"//g' aa |awk '{print $5,$6}'` >> $2
29     echo "#" >> $2
30 #文件存在
31 else    
32     #文件为空
33     if [ ! -s $2 ]; then
34         echo "file is empty"
35     #文件不空
36     else
37         #第一行不是“#!/bin/bash”
38         firstLine=`sed -n '1p' $2`
39         #字符串比较符两边一定要有空格
40         if [ "$firstLine" != "#!/bin/bash" ]; then
41             echo "Error command" && exit
42         #第一行是“#!/bin/bash”
43         else
44             #使用vim打开脚本;把光标直接定位至最后一行
45             vim + $2
46             #关闭文件
47             
48             #判断脚本有无语法错误
49             bash -n $2
50             #有语法错误
51             if [ $? -ne 0 ]; then
52                 echo "$2 has grammar mistakes"
53                 read -p "Pls input y(continue this edit)/n(quit without saved): " choice
54                 while true;do
55                     if [[ $choice == y ]] ;then
56                         #继续编辑
57                         vim + $2
58                     elif [[ $choice == n ]] ;then
59                         exit 1
60                     else
61                         echo -n "Error,"
62                     fi
63                     read -p "Input again y(continue this edit)/n(quit without saved): " choice
64                 done
65             else
66                 #赋予文件执行权限
67                 chmod +x $2
68             fi
69         fi        
70     fi
71 fi

运行命令是: 

mkscript.sh '[-D|--description "script description"] [-A|--author "script author"]'  test

原文地址:https://www.cnblogs.com/yajing-zh/p/4925780.html