3

Sorry for the subject clone, but given that the technique I used successfully from that answer doesn't work as expected on a new script, I figured it was time for a new question.

Anyway, the following script is fairly straight forward:

missed_symbols=()

grep missed ${dest}/scribe.log | while read -r line; do
  symbol=$(echo "${line}" | cut -d' ' -f1)
  missed_symbols+=("$symbol")
done

grep missed ${dest}/scribe_close.log | while read -r line; do
  symbol=$(echo "${line}" | cut -d' ' -f1)
  missed_symbols+=("$symbol")
done

for symbol in "${missed_symbols[@]}"; do
  echo "Scribe missed a turn in ${symbol}"
done
echo "Scribe missed ${#missed_symbols[@]} turns today"
exit 0

And adding -x to the #!/bin/bash line tells me that, indeed, it is assigning the first word of each $line from $missed_symbols[@] to $symbol. Yet, when I check ${#missed_symbols[@]}, I get zero. And, of course, looping through it produces no output.

So, where's my typo?

Community
  • 1
  • 1
pdm
  • 1,027
  • 1
  • 9
  • 24
  • See [BashFAQ #24](http://mywiki.wooledge.org/BashFAQ/024). – Charles Duffy Nov 21 '16 at 21:36
  • 1
    Tip: [shellcheck](http://www.shellcheck.net) automatically recognizes many common issues [like this](https://github.com/koalaman/shellcheck/wiki/SC2031) – that other guy Nov 21 '16 at 21:49
  • 1
    BTW -- using `cut` is bad form here; I really should have corrected that in my answer earlier rather than retaining it. See [BashFAQ #100](http://mywiki.wooledge.org/BashFAQ/100) for a general discussion of good practices for string manipulation in bash, or [the bash-hackers page on parameter expansion](http://wiki.bash-hackers.org/syntax/pe) for an in-depth discussion of the specific approach my updated answer is now using. – Charles Duffy Nov 21 '16 at 22:22
  • The stuff I write is almost always super simple, so I'm going to be making heavy use of ShellCheck. – pdm Nov 22 '16 at 15:52
  • Thank you, Charles, for your answer as well as clarification, even though this was a dupe. It's always nice when someone gives you the code you actually need to fix the problem, despite the answer being elsewhere in another form. – pdm Nov 22 '16 at 15:53
  • Please consider that your audience here is (obviously) not comprised of just "gents", and normalise the use of gender neutral language as much as you can. We want everyone to feel welcome here, thanks! – halfer Nov 23 '16 at 18:29

1 Answers1

4

Pipelines create subshells. Changes to shell variables made in subshells disappear when those subshells exit.

Thus, instead of piping into a while read loop, redirect from a process substitution:

while read -r line; do
  symbol=${line%%" "*}
  missed_symbols+=("$symbol")
done < <(grep missed ${dest}/scribe.log)
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441