【Shell】传参修改配置文件
描述:某程序利用到了一个配置文件,配置文件中有一行配置每次都需要手工修改,修改的内容是有规律的,规律为当前的系统时间+01,当然也有02或03的可能,大部分为01的情况
参数文件如下(模拟):
1 2 3 4 5 |
[root@mss conf]# cat init.conf [init] isb = 1 bno = 2019053101 [root@mss conf]# |
每次运维人员都需要手工修改2019053101,格式即为当天的日期+01,我们都清楚,如果人工修改的话“墨菲定律”就有可能发生,总有忘记修改或者修改错的时候,为了避免这种情况的发生,通过一小段儿shell脚本,自动修改,在每次执行程序之前,先执行shell,或者直接整合到一起。
shell如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
[root@mss script]# cat step1.sh #!/bin/bash source ~/.bash_profile #设置路径及将参数赋值给变量 Dir=/file/path/conf par=$1 # 帮助,告诉使用者,参数只能是1-4或者空 usage() { echo "Usage: sh step1.sh [Parameters can only be 1-4 or empty]" exit 1 } # 判断参数是否为空 is_null(){ if [ -z "${par}" ];then return 1 else return 0 fi } # 开始执行脚本,删除指定路径下的文件的指定行,也就是下面代码的sed -i '/bno/d' ${Dir}/init.con这一样 start(){ is_null if [ $? -eq "0" ]; then Bno=0${par} echo ${Bno} else Bno=01 echo ${Bno} fi curDate=$(date "+%Y%m%d")${Bno} sed -i '/bno/d' ${Dir}/init.con eval printf "%.s\#" {1..80} echo echo "Before the batch number is modified" cat ${Dir}/init.con # 将修改后的参数,写入配置文件中 echo "bno = "${curDate} >> ${Dir}/init.con eval printf "%.s\*" {1..80} echo echo "After the batch number is modified" cat ${Dir}/init.con eval printf "%.s\#" {1..80} echo } case "${par}" in "1"|"2"|"3"|"4"|"") start ;; *) usage ;; esac [root@mss script]# |
小结:写的有点儿啰嗦了,其实以下两句话就搞定,之所以这样写,主要是避免一些不必要的错误。
sed -i ‘/bno/d’ ${Dir}/init.con
echo “bno = “${curDate} >> ${Dir}/init.con