为什么在docker-compose命令中变量赋值不按预期工作?

huangapple go评论47阅读模式
英文:

Why variable assignment doesn't work as expected in docker-compose commands?

问题

以下是翻译后的内容:

我在我的docker-compose.yml文件中有以下内容:

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      a=1899
      echo "The value of \"a\" is $a"
    '

当我运行它时,我看到The value of "a" is .,所以出于某种原因,变量赋值不像我期望的那样工作。你知道发生了什么吗?

我尝试简化我的Docker Compose到最小程度,但问题仍然存在。我期望变量赋值和输出与bash脚本中的相同。

英文:

I have the following in my docker-compose.yml:

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      a=1899
      echo "The value of \"a\" is $a"
    '

And when I run it, I see The value of "a" is ., so for some reason, the variable assignment is not working as I would expect. Do you know what's going on?

I tried simplifying my docker compose to the very minimum, but still the same problem. I would expect that variable assignment and outputing would be the same than in a bash script.

答案1

得分: 1

你需要转义$符号。如果不转义这个符号,那么它将尝试从主机环境而不是Docker容器内部获取值。

所以你可以将你的命令更改为:

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      a=1899
      echo "The value of \"a\" is $$a"
    '

如果你想要从主机传递它,你可以这样做:

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      echo "The value of \"a\" is $a"
    '
a=1899 docker-compose up
英文:

You will need to escape the $ sign. If you do not escape the sign, then it will try to take the value from your host environment rather that from inside the docker container.

So you can change your command to

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      a=1899
      echo "The value of \"a\" is $$a"
    '

If you want to pass it from host instead, you can do this instead

my-service:
  image: amazon/aws-cli
  entrypoint: /bin/sh -c
  command: >
    '
      echo "The value of \"a\" is $a"
    '
a=1899 docker-compose up

huangapple
  • 本文由 发表于 2023年2月6日 09:25:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定