wc in background does not return

95 views Asked by At

In what scenario will a wc -l in bg not return?

And the case below in particular

I have a snippet similar to the one below in a shell script,

file_name=my_file_name.xyz

In one loop,

wc -l ${file_name} & bg_pid=$!

In another loop,

wait ${bg_pid}

I actually have an array of file_names and I put the wc -l for each in the background and wait on their pids in another loop.

wc -l on these files when done in the foreground gets completed. However, wc -l does not return when put in bg


Actually I want to do

count[i]=`wc -l ${file_name[i]}` & bg_pid=$!

This wouldn't work either cause bg process can't return a value that way (and I don't want to write to a file)

2

There are 2 answers

1
Mark Setchell On BEST ANSWER

To answer your question at the top of your post, "wc -l" in background will not return when the input stream to wc doesn't provide end of file, so if you do this, for example:

cat - | wc -l

and then don't type anything.

1
Louis On

Ok, so you are wondering why in your code wc -l might not return, right? Consider this command:

wc -l ${file_name}

If ${file_name} evaluates to the empty string, then you are running:

wc -l

which reads on stdin until stdin ends. If nothing is closing wc's stdin then wc will wait, and wait.... and wait.....