【问题标题】:Command returns a list of strings, but want to make it an array so I can iterate through them [duplicate]命令返回一个字符串列表,但想让它成为一个数组,这样我就可以遍历它们[重复]
【发布时间】:2021-03-10 23:57:17
【问题描述】:

我有这个命令,在比较两个不同的 git 分支时,它给了我一个目录列表:

git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u

k8s
postgres
scripts

我想遍历它返回的值(在本例中为 k8spostgresscripts)。

我不知道如何将这些值转换为数组。我尝试了几件事:

changedServices=$(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)

它只是将其视为多行字符串。

以及以下带有错误消息的...

declare -a changedServices=$(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)

declare: changedServices: inconsistent type for assignment

我将如何将此列表解析为数组?

【问题讨论】:

  • Bash 还是 zsh?您所指的答案是 zsh 特定的。
  • @BenjaminW。最终,这将在 CI/CD 管道中结束,并简要查看 Azure DevOps Pipeline 文档,我看不到任何关于它使用zsh 命令的信息。所以这很可能需要bash
  • 那么mapfile 答案应该可以工作:)

标签: bash git


【解决方案1】:

var=$() 是一个字符串赋值。对于不包含 $ 的数组,您也可以使用 mapfile,因为它通常是更好的选择

mapfile -t changedServices < <(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)

-t 选项删除尾随分隔符。

如果你没有地图文件,你可以做的另一件事是

changedServices=()

while IFS= read -r line; do
    changedServices+=("${line}")
done < <(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)

【讨论】:

  • 逐字读取一行:while IFS= read -r line -- 没有IFS=,则删除前导和尾随 IFS 字符:printf " %s \n" foo bar | { read -r first; IFS= read -r second; declare -p first second; }
猜你喜欢
  • 2023-04-04
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 2018-01-31
相关资源
最近更新 更多