【问题标题】:Passing a parameter's value to shell function prints only the name of the parameter将参数的值传递给 shell 函数只打印参数的名称
【发布时间】:2019-09-03 10:41:26
【问题描述】:

我需要向我的 shell 函数传递一个参数,如下所示:

function deploy {

        docker create \
        --name=$1_temp \
        -e test_postgres_database=$2 \
        -e test_publicAddress="http://${3}:9696"\
        # other irrelevant stuff

我正在传递以下参数:

deploy test_container test_name #1 test_database #2 ip_address #3

因此,当我传递这 3 个参数时,会根据它们创建一个新容器。但是,第三个参数有些特殊。所以还有另外一个函数,获取容器的ip。

function get_container_ip_address {
    container_id=($(docker ps --format "{{.ID}} {{.Names}}" | grep $1))
    echo $(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${container_id[0]})

所以,部署函数的执行实际上是这样的:

ip_address=$(get_container_ip_address test_container)
deploy test_container test_database ip_address

假设容器的 IP 地址是 1.1.1.1,那么ip_address=1.1.1.1。 但是,当我执行脚本并创建容器时,它的 IP 地址是: "http://ip_address:9696" 而不是 "http://1.1.1.1:9696"

我还尝试了以下方法:

...
-e test_publicAddress="http://$3:9696"\
...

但我仍然得到相同的结果。有没有办法可以获取传递参数的值?顺便说一句,我确信它包含所需的 IP 地址,因为我在其他地方(不是在函数中)使用它并且我打印了它以进行测试。提前谢谢!

【问题讨论】:

  • 您是否只将1.1.1.1ip_address 1.1.1.1 传递给脚本?
  • @LinPy 基本上,我执行ip_address=$(get_container_ip_address test_container),然后直接执行deploy test_container test_database ip_address(它使用这三个参数执行部署函数——名称、数据库、ip_address)。所以此时ip_address 应该有1.1.1.1 作为一个值(我已经在代码的其他地方测试过,它会打印出来)。

标签: bash shell docker parameters


【解决方案1】:

所以这样运行:

ip_address=$(get_container_ip_address test_container)

deploy test_container test_database $ip_address

当你在没有$ 的情况下调用它时,脚本不要管它,就像一个字符串ip_address

【讨论】:

  • 你(几乎)总是在变量引用周围加上双引号,所以使用"$ip_address" 而不是只使用$ip_address。 IP 地址无关紧要(除非有人用IFS 玩奇怪的游戏),但不带引号的变量引用是个坏习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
相关资源
最近更新 更多