Linux—shell腳本化工具模板

shell腳本介紹

  在研發過程當中,不斷的有項目或者產品升級,在此過程當中,咱們能夠充分利用shell腳本去實現一些固定步驟的一鍵部署和升級。linux

配置文件

  在編寫腳本前,咱們能夠編寫一個額外的配置文件做爲一鍵部署的入參文件,腳本能夠讀取到該配置文件中的變量值。屆時,只須要修改配置文件內的配置,而無需更改腳本。
如:test.propertiesshell

[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.propertiestest.sh放到一個目錄下,以便於讀取配置。vim

[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
相關文章
相關標籤/搜索