【问题标题】:For loop to check for fonts by name according to list in array returning repeating listFor循环根据返回重复列表的数组中的列表按名称检查字体
【发布时间】:2020-03-12 21:42:06
【问题描述】:

多亏了这里的乐于助人的人,我已经完成了大部分工作,但我仍然摸不着头脑......我有一个字体列表,我需要确认它们是否安装在 Mac 上,作为构建后检查的一部分。我想要一个 for 循环来针对 ${fontArray} 中的每个项目运行 system_profiler 命令。如果找不到字体,我想将 $I 添加到 ${missingFonts} 以便在脚本完成后将其打印在报告中的一行上。如果找到字体,我希望它只为其他一些变量设置值。稍后,我检查 ${missingFonts} 是否为空,如果是,则为 PASS,如果不是,则为 FAIL,我想回显 ${missingFonts} 的内容。这是我当前的代码...

  Var19=Fonts
fontArray=("font1" "font2" "font3")
missingFonts=()

for i in "${fontArray[@]}"; do
    system_profiler SPFontsDataType | grep "Full Name: $i" | sed 's/.*: //'
    if ! system_profiler SPFontsDataType | grep -q "Full Name: $i";  then 
        missingFonts+=( "$i" );
    fi
done

if [ ${#missingFonts[@]} -eq 0 ]; then
    Val19="Fonts Installed"
    Check19=PASS
else
    Val19="Missing Fonts: ${missingFonts[@]}"
    Check19=FAIL
fi

Line19=" | ${Check19} | ${Var19}        = ${Val19} "

echo "$Line19"

exit0

因为这些不是我希望得到的字体:

 FAIL | Fonts        = Missing Fonts: font1 font2 font 3

相反,我得到:

| FAIL | Fonts      = Missing Fonts: font1 font2 font3 
font1 font2 font3

当我使用我知道的字体的实际名称时,我只会在 ${fontArray} 中得到一长串字体,一次一个,然后循环

realFont1
realFont2
realFont3
realFont1
realFont2

直到我打断。

我不明白为什么它会在失败时打印两次名称,也不明白为什么它只是一一打印字体并在找到它们时多次循环列表。我对此还是很陌生,几乎无法管理“你好,世界!” 6 个月前,所以我很感谢您的建议。

【问题讨论】:

  • 把你的代码放在这个网站上:shellcheck.net。您的脚本中有一些错误。 fontArray 未正确定义,var19 从未使用过。但是你以后有val19...
  • 我在清理代码时对 fontArray 中的 " 进行了粗手指操作。Var19 在其他地方的不同函数中使用。

标签: bash macos shell sorting for-loop


【解决方案1】:
fontArray=("font1" "font2" "font3")
missingFonts=()
for i in "${fontArray[@]}"; do
    if ! system_profiler SPFontsDataType | grep -q "Full Name: $i";  then 
        missingFonts+=( "$i" );
    fi
done

if [ ${#missingFonts[@]} -eq 0 ] ; then
    Val19="Installed"
    Check19=PASS
else
    Val19="Missing Fonts: ${missingFonts[@]}"
    Check19=FAIL
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2021-12-17
    相关资源
    最近更新 更多