如何将关联数组中的变量和循环中的多行字符串打印到定界符中

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

我需要将变量(从 1 到 4)和关联数组中的选定值返回到定界文档中。

变量

BASE=ppp-multi-image
DEV=sdb # i.e. sdb or mmcblk0
ATTR=RequiredPartition,LegacyBIOSBootable
SIZE=11GiB

关联数组

declare -A NameUrl
NameUrl[uboot]=https://uboot.ext
NameUrl[arch]=https:/archlinux.ext
NameUrl[manjaro]=https://manjaro.ext
NameUrl[mobian]=https://mobian.ext
NameUrl[extra]=https://extra.ext
$ sudo sfdisk /dev/$DEV --wipe always <<EOF
label: gpt
first-lba: 64
table-length: 10
attrs=RequiredPartition, type=D7B1F817-AA75-2F4F-830D-84818A145370, start=64, size=32704 name="$BASE-<# how do I return "uboot" here as first variable? #>"

for NameUrl in "${!NameUrl[@]}"; do
echo "attrs=\"$ATTR\", size=$SIZE, name=\"$BASE-${NameUrl}\""
done | sort
<# this loop is not returned into EOF string #>

attrs="$ATTR", size=+, name="extra"
EOF

最终结果应该如下所示

$ sfdisk /dev/sdb --wipe always <<EOF
label: gpt
first-lba: 64
table-length: 10
attrs=RequiredPartition, type=D7B1F817-AA75-2F4F-830D-84818A145370, start=64, size=32704 name="ppp-multi-image-uboot"
attrs="RequiredPartition,LegacyBIOSBootable", size=11GiB, name="ppp-multi-image-arch"
attrs="RequiredPartition,LegacyBIOSBootable", size=11GiB, name="ppp-multi-image-manjaro"
attrs="RequiredPartition,LegacyBIOSBootable", size=11GiB, name="ppp-multi-image-mobian"
attrs="RequiredPartition,LegacyBIOSBootable", size=+, name="extra"
EOF
arrays bash for-loop eof
1个回答
0
投票

您不能将 shell 代码直接嵌入到定界文档中。 shell 应该如何识别它是代码而不是数据?整个想法有不好的代码味道,但如果出于某种原因你认为这是你最好的选择(而不是,比如说,将适当的数据通过管道输送到命令的标准输入中),那么你可以利用命令替换的事实在此处文档中执行,前提是分隔符词不带引号。 此外,您似乎不仅想取出“uboot”,还想取出“extra”作为特殊情况。您可以在

for

循环中执行此操作,只需测试这些键并且不为它们生成任何输出,而将它们单独处理。但是,我会考虑从

NameUrl
数组中省略它们,或者创建一个单独的数组来省略它们。
例如:

$ sudo sfdisk "/dev/$DEV" --wipe always <<EOF label: gpt first-lba: 64 table-length: 10 attrs="RequiredPartition, type=D7B1F817-AA75-2F4F-830D-84818A145370, start=64", size=32704 name="${BASE}-uboot" $( for name in "${!NameUrl[@]}"; do case ${name} in uboot|extra) continue ;; esac printf '%s\n' "attrs=\"$ATTR\", size=$SIZE, name=\"$BASE-${name}\"" done | sort ) attrs="$ATTR", size=+, name="extra" EOF

© www.soinside.com 2019 - 2024. All rights reserved.