Bash 命令返回字符串列表,但希望将其设置为数组,以便我可以遍历它们
我有一个命令,当比较两个不同的git分支时,它会给我一个目录列表,其中有更改:Bash 命令返回字符串列表,但希望将其设置为数组,以便我可以遍历它们,bash,git,Bash,Git,我有一个命令,当比较两个不同的git分支时,它会给我一个目录列表,其中有更改: git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u k8s postgres scripts 我希望遍历它返回的值(在本例中为k8s,postgres,以及脚本) 但我不知道如何将这些值转换为数组。我试过两种方法: changedServices=$(git diff test production --name
git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u
k8s
postgres
scripts
我希望遍历它返回的值(在本例中为k8s
,postgres
,以及脚本
)
但我不知道如何将这些值转换为数组。我试过两种方法:
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
如何将此列表解析为数组?var=$()
是一个字符串赋值。对于阵列,您不包括$
,但也可以使用mapfile,因为它通常是一个更好的选项
mapfile -t changedServices < <(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)
Bash还是zsh?您所指的答案是特定于zsh的。@BenjaminW。最终,这将在一个CI/CD管道中结束,简单地看一下Azure DevOps管道文档,我没有看到任何关于它使用
zsh
命令的内容。因此,这很可能需要一个bash
。然后mapfile
答案应该可以:)逐字读取一行:,而IFS=read-r line
——不带IFS=
,然后删除前导和尾随的IFS字符:printf“%s\n”foo bar |{read-r first;IFS=read-r second;declare-p first second;}
changedServices=()
while IFS= read -r line; do
changedServices+=("${line}")
done < <(git diff test production --name-only | awk -F'/' 'NF!=1{print $1}' | sort -u)