Running echo "This is a test" | wc -w > num_words
results in the contents of the file num_words
being "4". This could also be accomplished with a shell script count_words_and_record.sh
:
#!/bin/bash
wc -w > num_words
Running echo "This is a test" | ./count_words_and_record.sh
has the same outcome.
The trouble is, I am a terribly impatient person, and I want to get on to other tasks without waiting for the words to be counted. So I run echo "This is a test" | wc -w > num_words &
, everything happens in the background, and I can run other commands immediately. Eventually, when the counting finishes, I get a message, and the contents of num_words
is then "4". However, if I instead modify the script
#!/bin/bash
wc -w > num_words &
and run echo "This is a test" | ./count_words_and_record.sh
, then the contents of ``num_words'' is "0" instead of "4".
What's going on here? Is there a way to modify the script to get the correct behavior?