Bash script to find included files in C code
... so what's going on?


$ (grep ^#include file.c | grep -o '"[^"]\+"' | read -a myarr; echo $myarr)
(nothing is printed)
$ (grep ^#include file.c | grep -o '"[^"]\+"' | mapfile myarr; echo $myarr)
(nothing is printed)



Why doesn't this work? Because "each command in a pipeline is executed in its own subshell". As the page explains, you could enable the lastpipe option to have the last element of the pipeline run in the current process. (The page doesn't mention that this will only work when you use it in a script, where job control is not active (as mentioned here). It won't work in an interactive shell.)

Keep pipelines as short as possible

It's good to use the fewest possible processes in pipelines.
Multiple grep in a pipeline are points to look at with suspicion.
You can make the first grep work a little harder,
using a stricter pattern, and then you can achieve the same result with 2 processes instead of 3:

grep '^#include .*"' file.c | cut -d'"' -f2