Arrays Bash脚本在for循环之后不继续
我想在bash中制作一个mac Clippy。以下是我的一些代码:Arrays Bash脚本在for循环之后不继续,arrays,bash,Arrays,Bash,我想在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 -- "Not
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
当我打开邮件时,它会发出回声并说:看起来你在试图发送电子邮件。需要帮忙吗?然后是一条新的线路。我打开了邮件和便笺。我如何才能使它继续扫描打开的应用程序,而不陷入for循环?我在您的代码中看到两个问题: 数组索引在Bash中以0开头;for循环使用1作为起始索引 在for循环中修改数组是不合适的;将数组重置命令置于外部
您正在循环期间清空阵列。因此,当尝试下一次迭代时,${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=()
以上代码应该适合您。
问题是数组是基于零的,因此您对assist_array[2]的引用实际上是一个空字符串。当你没有什么要说的时候,它会读到stdin
另外,正如其他答案明确或隐含地指出的那样,您正在for循环内初始化数组。你不应该这么做,因为你还没有读完它
所以,基本上,你只是坚持说等待标准输入。您可以按Ctrl-D结束当前程序上的标准输入 哇!发帖后12分钟内有三个答案!我希望在我开始编写代码时它们有堆栈溢出。真见鬼!我希望我开始编码时他们能上网!我知道。我在mac上运行了它,发现它比原来的clippy更烦人,也没什么用处,所以你已经超越了微软。你可能有兴趣在你的程序中加入一个睡眠来降低它的音量。这只是程序的一个片段,因此程序可以复制。
for (( i=0; i<${arraylength}; i++ )); do
echo "${assist_array[i]}"
say "${assist_array[i]}"
done
assist_array=()
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