You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell中使用for循环创建列表,解决镜像标签拼接报错问题

错误原因

你写的r_madoori1/$i会被Shell识别为可执行命令尝试运行,你的环境中没有对应同名的可执行文件,因此抛出找不到文件/目录的报错。你需要将该字符串输出而非作为命令执行。

修复代码

写法1:适配所有POSIX Shell的写法

Images="alpine ubuntu centos"

Image_tags="$(for i in $Images; do
  echo "r_madoori1/$i"
done | tr '\n' ' ' | sed 's/ *$//')"

echo "$Image_tags"

写法2:Bash专属更稳妥的数组写法(避免镜像名带空格的异常)

# 定义原始镜像数组
Images=(alpine ubuntu centos)
# 拼接前缀生成新数组
Image_tags=()
for img in "${Images[@]}"; do
  Image_tags+=("r_madoori1/$img")
done
# 转为空格分隔的字符串
result="${Image_tags[*]}"
echo "$result"
运行效果

两种写法的输出均为你预期的:

r_madoori1/alpine r_madoori1/ubuntu r_madoori1/centos

内容的提问来源于stack exchange,提问作者Yagami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 03:54:04