[svc]entrypoint.sh shell腳本解析

最近搞influxdb繪圖,看到其dockerfile的entry.sh,無奈看的不是很懂. 因而查了下..html

docker run 經過傳參實現配置文件覆蓋

實現啓動鏡像時候可指定配置文件
    若是不指定,使用默認的配置
    若是指定,即便用指定的配置

參考:
https://hub.docker.com/_/influxdb/
https://github.com/influxdata/influxdata-docker/blob/master/influxdb/1.4/entrypoint.shgit

docker run -p 8086:8086 \
      -v $PWD/influxdb.conf:/etc/influxdb/influxdb.conf:ro \
      influxdb -config /etc/influxdb/influxdb.conf

從dockerfile入手github

...
ENTRYPOINT ["/entrypoint.sh"]
CMD ["influxd"]

在看下entrypoint.shdocker

#!/bin/bash
set -e

if [ "${1:0:1}" = '-' ]; then
    set -- influxd "$@"           # -> influxd -conf 1 2 3
fi

if [ "$1" = 'influxd' ]; then
    /init-influxdb.sh "${@:2}"    # -> /init-influxdb.sh -conf 1 2 3
fi

echo $@
#exec "$@"                        # -> influxd -conf 1 2 3

徒手執行entry.sh測試shell

$  sh entrypoint.sh 1 2 3
1 2 3
1 2 3
$  sh entrypoint.sh -conf 1 2 3
influxd - 1 2 3
init-influxdb.sh -conf 1 2 3

可見若是加了 -conf就會賦值數組

爲了便於弄清原理,修改entrypoint.sh來測測bash

#!/usr/bin/env bash

set -e

if [ "${1:0:1}" = '-' ]; then
    set -- influxd "$@"                   # -> influxd -conf 1 2 3
fi

echo $@

if [ "$1" = 'influxd' ]; then
    echo "/init-influxdb.sh "${@:2}""    # -> /init-influxdb.sh -conf 1 2 3
fi

echo $@
#exec "$@"                               # -> influxd -conf 1 2 3
$  sh entrypoint.sh 1 2 3
1 2 3
1 2 3
$  sh entrypoint.sh -conf 1 2 3
influxd - 1 2 3
/init-influxdb.sh -conf 1 2 3
influxd -conf 1 2 3
可見這個腳本本質實現的是:
若是
    sh entrypoint.sh influxd
    influxdb
若是
    sh entrypoint.sh -config 1 2 3
    influxdb -conf 1 2 3

細節知識點測試

shell中截取字符串和數組

## ${str:a:b}含義
參考: https://zhidao.baidu.com/question/559065726.html

${str:a:b}  表示提取字符串a開始的b個字符
 
str="abcd"
echo ${str:0:3}
結果是abc


## 數組獲取選項
參考: https://unix.stackexchange.com/questions/249869/meaning-of-101

arr=(1 2 3 4 5)
#輸出第一項
echo ${arr[1]}

#輸出全部項
echo ${arr[@]}

#截取數組選項-從第3項到最後一項
echo ${arr[@]:3}
4 5

從第0項到第一項
echo ${arr[@]:0:3}
1 2 3


## 判斷第一個選項的第一個字符
if [ "${1:0:1}" = '-' ]

set env exec環境變量

sh 1.sh,開子bash執行完畢腳本

name="maotai"
$ cat 1.sh
#!/bin/bash
echo $name

# 未輸出任何(子bash沒繼承set的變量)

source 1.sh,不開啓子bash: source不會開子bash

name="maotai"
$ cat 1.sh
echo $name

# 輸出maotai

小結:this

exec,不會開子bash,會把進程生命賦給要執行的命令 
exec命令在執行時會把當前的shell process關閉,而後換到後面的命令繼續執行

bash shell的命令分爲兩類:外部命令和內部命令
參考(很經典):http://www.cnblogs.com/zhaoyl/archive/2012/07/07/2580749.html
http://blog.csdn.net/clozxy/article/details/5818465.net

以前還繪製了圖說明set和env關係:

使用set設置變量: 實現形參移位

參考:
https://unix.stackexchange.com/questions/308260/what-does-set-do-in-this-dockerfile-entrypoint

$ set a b c
$ echo $1
a
$ echo $2
b
$ echo $3
c


set -- influxdb "$@"

$ echo $1,$2,$3
a,b,c
$ set -- influxdb "$@"
$ echo $1,$2,$3,$4   
influxdb,a,b,c

$# $@的區別

$# 將全部參數當成字符串,賦值給全部
$@ 將全部參數看成數組,一項一項賦值
直觀體驗

for i in "$@";do
    echo $i
done

echo "----------------------"
for i in "$*";do
    echo $i
done
相關文章
相關標籤/搜索