shell脚本介绍
在研发过程中,不断的有项目或者产品升级,在此过程中,我们可以充分利用shell脚本去实现一些固定步骤的一键部署和升级。
配置文件
在编写脚本前,我们可以编写一个额外的配置文件作为一键部署的入参文件,脚本可以读取到该配置文件中的变量值。届时,只需要修改配置文件内的配置,而无需更改脚本。
如:test.properties
[root@linux01 ~/test_sh]# vim test.properties
# set parameters start
# int type
id_test=12
# string type
str_test="test properties"
# array with white space type
array_test=(arr1 arr2 arr3)
[root@linux01 ~/test_sh]# ll
-rw-r----- 1 root root 159 Mar 16 21:43 test.properties
shell实战
[root@linux01 ~/test_sh]# vim test.sh
#!/bin/bash
# print start time
starttime=$(date +%Y-%m-%d\ %H:%M:%S)
# echo to log
echo "【Start to execute the script】, start time is: " $starttime >> test_sh.log
# read properties from other file
source ./test.properties
echo "Parameters: cat test.properties" >> test_sh.log
while read line
do
echo $line >> test_sh.log;
done < test.properties
echo "------ test.properties end------" >> test_sh.log
# ==============================================================
# create dir
mkdir ${str_test}${id_test}
echo -e "\nmkdir dir success, and name is: "${str_test}${id_test} >> test_sh.log
# product file
for ((i=0; i<${#array_test[@]}; i++))
do
echo "now array_test i is "${#array_test[@]} >> test_sh.log
echo "This is ${array_test[i]} file " >> ${array_test[i]}_file.txt
done
# print end time
endtime=`date +"%Y-%m-%d %H:%M:%S"`
[root@linux01 ~/test_sh]# ll
-rw-r----- 1 root root 159 Mar 16 21:43 test.properties
-rwxr-x--- 1 root root 993 Mar 16 21:45 test.sh
执行shell
注意为了简化,我们将test.properties
和test.sh
放到一个目录下,以便于读取配置。
[root@linux01 ~/test_sh]# sh test.sh
[root@linux01 ~/test_sh]# ll
total 28
-rw-r----- 1 root root 19 Mar 16 22:11 arr1_file.txt
-rw-r----- 1 root root 19 Mar 16 22:11 arr2_file.txt
-rw-r----- 1 root root 19 Mar 16 22:11 arr3_file.txt
-rw-r----- 1 root root 159 Mar 16 22:08 test.properties
drwxr-x--- 2 root root 4096 Mar 16 22:11 test_properties12
-rwxr-x--- 1 root root 969 Mar 16 22:11 test.sh
-rw-r----- 1 root root 469 Mar 16 22:11 test_sh.log
查看日志
[root@linux01 ~/test_sh]# vim test_sh.log
【Start to execute the script】, start time is: 2020-03-16 21:57:47
Parameters: cat test.properties
# set parameters start
# int type
id_test=12
# string type
str_test="test properties"
# array with white space type
array_test=(arr1 arr2 arr3)
------ test.properties end------
mkdir dir success, and name is: test_properties_12
now array_test i is 3
now array_test i is 3
now array_test i is 3
【Execute the script end】, end time is: 2020-03-16 21:57:47
查看生成的文件
[root@linux01 ~/test_sh]# vim arr1_file.txt
This is arr1 file
[root@linux01 ~/test_sh]# vim arr2_file.txt
This is arr2 file
[root@linux01 ~/test_sh]# vim arr3_file.txt
This is arr3 file
网友评论