【问题标题】:bash script put all parameters inside single quotesbash脚本将所有参数放在单引号内
【发布时间】:2022-07-21 18:54:48
【问题描述】:

我们有 docker contianers,我想通过脚本在我的容器中运行 bash 命令。像这样:

bin/run-in-container ls -la

在容器中运行的脚本如下所示:

#!/usr/bin/env bash

docker compose exec container_name bash -ic "$@"

我无法让我的脚本解释单引号内的所有参数。

this interprets to docker compose exec api bash -ic ls -la
but what I want to to interpret is docker compose exec api bash -ic 'ls -la'

如果我尝试连接一串单引号和我的参数,它会使字符转义:

#!/usr/bin/env bash

escaped_single_qoute="'"
docker compose exec container_name bash -ic $escaped_single_qoute "$@" $escaped_single_qoute

但这解释为:

docker compose exec api bash -ic ''\''ls' '-la'\'''

【问题讨论】:

  • 为什么不只是docker compose exec container_name "$@"But this interprets into :是的,类型的引号连接起来时它们是不同的,有不同的解析规则。
  • 这在容器内的行为不正确。这只运行 ls 而不是 ls -la 或类似 ls src/test
  • 我无法复制您的评论。使用version: "3" services: alpine: image: alpine command: sleep 1h,后跟docker compose updocker compose exec alpnie ls -la 正确列出/ 目录。发布 MCVE,否则没有发生。

标签: linux bash docker shell docker-compose


【解决方案1】:

如果要传递单个命令,只需传递命令:

docker compose exec container_name "$@"
# usage example: ./script ls -la
# usage example: ./script sh -c "ls -la ; echo another command"

如果您想在 bash 交互式 shell 中运行命令时传递具有(奇怪?)要求的单个命令,您可以转发参数并在 shell 中执行它们:

docker compose exec container_name bash -ic '"$@"' _ "$@"
# usage example: ./script ls -la
# usage example: ./script sh -c "ls -la ; echo another command"

如果你想传递一个 shell 脚本,就像 eval 一样,只需用空格连接参数即可:

docker compose exec container_name bash -ic "$*"
# usage example: ./script ls -la
# usage example: ./script ls -la ';' echo another command
# usage example: ./script "$(printf "%q " sh -c "ls -la ; echo another command")"

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2020-06-02
    • 2021-11-11
    • 1970-01-01
    • 2010-12-31
    • 2017-10-31
    • 2011-03-12
    相关资源
    最近更新 更多