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

问题描述 投票:0回答:1

我有一个脚本是这样的

#!/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 jq '.[0].Mountpoint') echo $volume createdir=$volume /var/lib/docker/volumes/volume_name/_data

当我给 mkdir -p /var/lib/docker/volumes/volume_name/_data/testdir. 它创造了它。我在替换方面做错了什么?

bash docker
1个回答
3
投票

你的问题是,因为你的 jq 调用缺少一个 -r 选项开关来输出一个原始字符串,而不是一个不能作为路径使用的JSON字符串。

参见 man jq:

--raw-output -r:
有了这个选项,如果过滤器的结果是一个字符串,那么它将被直接写入标准输出,而不是被格式化为一个带引号的JSON字符串。这对于让jq过滤器与非JSON系统对话是很有用的。

另外,为了防止路径的分词,一定要在变量的扩展周围加上双引号。

我在代码的注释中详细说明了双引号是可选的或必须的情况;不过,在有疑问的情况下,加双引号是安全的,除了特殊情况的。

  • 明确可取的单词分割或模式的球状匹配。
  • 作为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"
© www.soinside.com 2019 - 2024. All rights reserved.