我正在试着在bash中做一个mac Clippy。下面是我的一些代码:
say "Hello there!"
declare -a assist_array=()
while true; do
if pgrep -xq -- "Mail"; then
assist_array+=('It looks like your trying to send an email. Would you like some help?')
fi
if pgrep -xq -- "Notes"; then
assist_array+=('It looks like your trying to take a note. Would you like some help?')
fi
arraylength=${#assist_array[@]}
for (( i=0; i<${arraylength}+1; i++ )); do
echo ${assist_array[i]}
say ${assist_array[i]}
assist_array=()
done
done当我打开邮件时,它会回显并说:"It looks like your trying to send an email. Would you like some help?"然后换一行。我打开了邮件和便笺。我如何才能让它继续扫描打开的应用程序,而不是陷入for循环?
发布于 2018-10-08 00:59:21
在循环期间,您正在清空数组。因此,当尝试下一次迭代时,${assist_array[i]}中没有要打印的内容。如果需要清空数组,请在循环结束后执行。
此外,数组索引从0到length-1,而不是从1到length。通常,您应该引用可能包含多个单词的变量。
for (( i=0; i<${arraylength}; i++ )); do
echo "${assist_array[i]}"
say "${assist_array[i]}"
done
assist_array=()发布于 2018-10-08 01:01:59
say "Hello there!"
declare -a assist_array=()
while true; do
if pgrep -xq -- "Mail"; then
assist_array+=('It looks like your trying to send an email. Would you like some help?')
fi
if pgrep -xq -- "Notes"; then
assist_array+=('It looks like your trying to take a note. Would you like some help?')
fi
arraylength=${#assist_array[@]}
for (( i=0; i<${arraylength}; i++ )); do
echo ${assist_array[i]}
say ${assist_array[i]}
done
assist_array=()
done上面的代码应该可以为你工作。问题是数组是从零开始的,所以您对assist_array2的引用实际上是一个空字符串。当你没有传递任何东西给"say“时,它将读取stdin。
此外,正如其他答案(显式或隐式地)指出的那样,您正在初始化for循环中的数组。你不应该这样做,因为你还没有读完它。
所以,基本上,你只是坚持等待stdin。您可以按Ctrl-D来结束当前程序上的stdin输入。
https://stackoverflow.com/questions/52690736
复制相似问题