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?

6
  • See BashFAQ #24. Commented Nov 21, 2016 at 21:36
  • 1
    Tip: shellcheck automatically recognizes many common issues like this Commented Nov 21, 2016 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 for a general discussion of good practices for string manipulation in bash, or the bash-hackers page on parameter expansion for an in-depth discussion of the specific approach my updated answer is now using. Commented Nov 21, 2016 at 22:22
  • The stuff I write is almost always super simple, so I'm going to be making heavy use of ShellCheck. Commented Nov 22, 2016 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. Commented Nov 22, 2016 at 15:53

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.