首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bash脚本在for循环后不能继续

Bash脚本在for循环后不能继续
EN

Stack Overflow用户
提问于 2018-10-08 00:50:16
回答 2查看 388关注 0票数 0

我正在试着在bash中做一个mac Clippy。下面是我的一些代码:

代码语言:javascript
复制
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循环?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-08 00:59:21

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

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

代码语言:javascript
复制
for (( i=0; i<${arraylength}; i++ )); do
    echo "${assist_array[i]}"
    say "${assist_array[i]}"
done
assist_array=()
票数 1
EN

Stack Overflow用户

发布于 2018-10-08 01:01:59

代码语言:javascript
复制
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输入。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52690736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档