gpt4 book ai didi

bash 脚本 - 使用变量创建目录

转载 作者:行者123 更新时间:2023-12-02 20:42:12 25 4
gpt4 key购买 nike

我有一个这样的脚本 -

#!/usr/bin/env bash

set -e

volume=$(docker volume inspect volume_name | jq '.[0].Mountpoint')
echo $volume
createdir=$volume/testdir
mkdir -p ${createdir}

但它不会在卷路径中创建任何目录。 echo $volume确实打印了正确的路径 - /var/lib/docker/volumes/volume_name/_data
当我给 mkdir -p /var/lib/docker/volumes/volume_name/_data/testdir .它创造了它。我做错了什么替换?

最佳答案

您的问题是因为您的 jq调用缺少 -r选项开关以输出原始字符串而不是不可用作路径的 JSON 字符串。

man jq :

--raw-output / -r:

With this option, if the filter´s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.


此外,为了防止路径分词,请始终在变量的扩展周围添加双引号。

我详细说明了代码注释中双引号是可选的或强制的情况;尽管有疑问,添加双引号是安全的,但以下特殊情况除外:
  • 明确期望的分词或模式匹配。
  • 作为 RegEx 模式的变量扩展。

  • 这是您的修复代码:

    #!/usr/bin/env bash

    # Expansion of sub-shell output does not need double quotes,
    # because it is a simple variable assignment.
    # It would be mandatory if the output was an argument to a command.
    volume=$(docker volume inspect volume_name | jq -r '.[0].Mountpoint')

    # Here double quotes are fancy optional but a good practice anyway.
    # If not present and volume contained a globbing pattern,
    # it would be expanded. It would also generate a path check access
    # to the file-system. Better be safe with double quotes.
    echo "$volume"

    # Here double quotes are optional because it is an assignment and not
    # an argument to a command.
    createdir=$volume/testdir

    # Here double quotes are mandatory,
    # as the variable is an argument to the mkdir command.
    mkdir -p -- "$createdir"

    关于bash 脚本 - 使用变量创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61388774/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com