本文主要介紹Linux的shell腳本,在實踐中總結出大致的部署升級腳本化模板。 ...
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