Bash脚本在for循环后无法继续

时间:2018-10-07 16:50:16

标签: 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 -- "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

当我打开Mail时,它会回显并说:"It looks like your trying to send an email. Would you like some help?",然后换一行。我同时打开了邮件和便笺。我如何才能使其继续扫描打开的应用程序而不会陷入for循环中?

3 个答案:

答案 0 :(得分:1)

您正在循环中清空数组。结果,当尝试下一次迭代时,${assist_array[i]}中没有要打印的内容。如果需要清空数组,请在循环结束后执行。

此外,数组索引从0length-1,而不是从1length。而且通常应该引用可能包含多个单词的变量。

for (( i=0; i<${arraylength}; i++ )); do
    echo "${assist_array[i]}"
    say "${assist_array[i]}"
done
assist_array=()

答案 1 :(得分:0)

我在您的代码中看到两个问题:

  • 数组索引在Bash中以0开头;您的for循环使用1作为起始索引
  • 不能修改for循环内的数组;将array reset命令放在外面

Map<String, int> test = new Map();
test.putIfAbsent('58', ()=> 56 );

答案 2 :(得分:0)

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

上面的代码应该对您有用。 问题在于数组是从零开始的,因此您对Assistant_array [2]的引用实际上是一个空字符串。当您什么都不传递给“ say”时,它将显示为stdin。

此外,正如其他答案所指出的(显式或隐式),您正在初始化for循环内的数组。您不应该像尚未阅读完本书那样去做。

因此,基本上,您只是坚持说等待标准输入。您可以按Ctrl-D结束当前程序上的标准输入。