歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> SHELL編程

shell編程 自動創建測試文件 升級版

相對於第一次寫的shell編程,本次變動為:使用shell函數,使代碼更簡潔,使用trap捕捉信號,不許ctrl+c強制退出,其他無改進,代碼如下:

trap "echo Error!!" SIGINT SIGTERM
echo $2|grep "[[:punct:]]" &> /dev/null && echo "Sorry! Filename only accept input(A-z or 0-9)" && exit 1
FTB=${2:-demo}
MaxArr=`ls ./|grep $FTB|grep -v ${FTB}.sh|cut -d"." -f1|awk -F"${FTB}" '{print $NF}'|sort -n|tail -1`
MaxFile=$((MaxArr+1))
Max=`ls ./|grep ${FTB}'[0-9][0-9]*'.sh|tail -1`
Havesame=`ls ./|grep -v ${FTB}'[0-9][0-9]*'.sh|grep ${FTB}`
Have1=`ls ./|grep ${FTB}|wc -l`
Create(){
        if [[ ! -f ./${FTB}.sh && -z $Max ]];then
                `touch ./${FTB}.sh;chmod 700 ./${FTB}.sh`
        #      echo "Create File ${FTB}.sh Success"
                echo -e '#!/bin/bash\n#Author: MOS\n'"#Date & Time: `date +%F/%T`\n#Version: 1.0.1\n#Description:\n#" > ./${FTB}.sh
                Res=`echo "${PWD}/${FTB}.sh"`
        elif [[ $Have1 = 1 && $Havesame = "${FTB}.sh" ]];then
                `touch ./${FTB}${Have1}.sh;chmod 700 ./${FTB}${Have1}.sh`
        #      echo "Create File ${FTB}${Have1}.sh Success"
                echo -e '#!/bin/bash\n#Author: MOS\n'"#Date & Time: `date +%F/%T`\n#Version: 1.0.1\n#Description:\n#" > ./${FTB}${Have1}.sh
                Res=`echo "${PWD}/${FTB}${Have1}.sh"`
        else
                  `touch ./${FTB}${MaxFile}.sh;chmod 700 ./${FTB}${MaxFile}.sh`
        #      echo "Create File ${FTB}${MaxFile}.sh Success"
                echo -e '#!/bin/bash\n#Author: MOS\n'"#Date & Time: `date +%F/%T`\n#Version: 1.0.1\n#Description:\n#" > ./${FTB}${MaxFile}.sh
                Res=`echo "${PWD}/${FTB}${MaxFile}.sh"`
        fi
}
if [[ -z $1 || $1 == "-c" && -n $2 ]];then
        Create
        echo $Res
elif [[ $1 = "-d" ]];then
        Create
        vim +$ $Res
        until bash -n $Res &> /dev/null ;do
        read -p "Syntax error!Are you sure you want to exit now?(y|n): " Quit
                if [[ $Quit == y ]];then
                        echo "Give up debug!!"
                        exit 1
                fi
        vim +$ $Res
        done
elif [[ $1 = "-m" ]];then
      Date=`date +%m-%d-%H:%M`
      mkdir -m 700 ./tmp$Date;mv *.sh ./tmp$Date
fi

相關鏈接:shell編程 自動創建測試文件 http://www.linuxidc.com/Linux/2012-09/71417.htm

Copyright © Linux教程網 All Rights Reserved