如何在docker-compose的command中传递bash动态日期变量?
解决方案
问题根源
Docker Compose 的 command 参数默认不会调用 Shell 解析命令替换(如 $(date)),且 Compose 自身会将 $ 视为变量插值语法,导致直接写 $(date) 会触发格式错误;若用 $$ 转义,传给容器的是未解析的命令字符串,而容器默认直接执行目标程序,不会解析 Shell 语法,因此报错。
方案1:通过容器内 Shell 解析命令替换
修改 docker-compose.yaml 的 command 字段,用 bash -c 包裹完整命令,让容器内的 Shell 负责解析 date 命令替换:
version: '3.3' services: gphotos: image: ghcr.io/gilesknap/gphotos-sync:3.1.0 container_name: gphotos restart: "no" stdin_open: true tty: true command: bash -c '/storage --progress --start-date "$(date +"%F" --date="3 month ago")"' ports: - '8080:8080'
此方案依赖容器镜像内置 bash 和 date 命令(该 gphotos-sync 镜像基于 Python 基础镜像,默认包含这些工具)。
方案2:宿主机预计算日期,通过环境变量传递
先在宿主机计算目标日期,通过环境变量传递给 Compose,避免容器内解析:
- 修改
docker-compose.yaml的command部分,引用环境变量:
version: '3.3' services: gphotos: image: ghcr.io/gilesknap/gphotos-sync:3.1.0 container_name: gphotos restart: "no" stdin_open: true tty: true command: >- /storage --progress --start-date "${START_DATE}" ports: - '8080:8080'
- 执行 Compose 时临时设置环境变量:
START_DATE=$(date +"%F" --date="3 month ago") docker-compose up
此方案无需依赖容器内的 Shell 工具,日期计算在宿主机完成后传递给容器。
内容的提问来源于stack exchange,提问作者nitobuendia
相关产品推荐
相关产品推荐

