:和:=在bash参数扩展中

时间:2015-05-20 21:13:49

标签: bash dockerfile

尝试理解用bash编写的dockerfile。 什么是:for?

: ${WORDPRESS_DB_USER:=root}

并且:=?

我从脚本中添加了更多代码供参考:

#!/bin/bash
set -e

if [ -n "$MYSQL_PORT_3306_TCP" ]; then
    if [ -z "$WORDPRESS_DB_HOST" ]; then
        WORDPRESS_DB_HOST='mysql'
    else
        echo >&2 'warning: both WORDPRESS_DB_HOST and MYSQL_PORT_3306_TCP found'
        echo >&2 "  Connecting to WORDPRESS_DB_HOST ($WORDPRESS_DB_HOST)"
        echo >&2 '  instead of the linked mysql container'
    fi
fi

if [ -z "$WORDPRESS_DB_HOST" ]; then
    echo >&2 'error: missing WORDPRESS_DB_HOST and MYSQL_PORT_3306_TCP environment variables'
    echo >&2 '  Did you forget to --link some_mysql_container:mysql or set an external db'
    echo >&2 '  with -e WORDPRESS_DB_HOST=hostname:port?'
    exit 1
fi

# if we're linked to MySQL, and we're using the root user, and our linked
# container has a default "root" password set up and passed through... :)
: ${WORDPRESS_DB_USER:=root}
if [ "$WORDPRESS_DB_USER" = 'root' ]; then
    : ${WORDPRESS_DB_PASSWORD:=$MYSQL_ENV_MYSQL_ROOT_PASSWORD}
fi
: ${WORDPRESS_DB_NAME:=wordpress}

1 个答案:

答案 0 :(得分:4)

:只是一个什么都不做的命令。但是,仍会评估该命令的参数。

${WORDPRESS_DB_NAME:=wordpress}是一个参数扩展,用于检查WORDPRESS_DB_NAME是否未设置或是否为值的空字符串。如果其中一个为真,则为参数赋值wordpress。然后,扩展的结果是WORDPRESS_DB_NAME的(可能是新分配的)值。

如果变量的值没有(非空)值,它们一起形成一个常用的shell习惯用法来设置它。

(非DRY)Python等效项可能是

try:
    if not WORDPRESS_DB_NAME:
        WORDPRESS_DB_NAME = "wordpress"
except NameError:
    WORDPRESS_DB_NAME = "wordpress"