July 29, 2010

“BASH pipes, sub-processes and variables”

While hacking on some init scripts, I learned that using a pipe with read to spawn sub-processes has an interesting side-effect on variables. This may save someone a little headache later on.

For example:

PIDS=""
ps ax | grep ruby | grep gearman | while read line
do
  pid=`echo $line | cut -f 1 -d ' '`
  PIDS="${PIDS},${pid}"
done
echo -n "..."

echo $PIDS # --> ""

This is definitely not the desired outcome. The side-effect of forking sub-processes is that variables are reset.

Here is the solution, forking, and then redirecting the output to the while read; do … done loop.

PIDS=""
while read line
do
  pid=`echo $line | cut -f 1 -d ' '`
  PIDS="${PIDS},${pid}"
done < <(ps ax | grep ruby | grep gearman)

echo $PIDS # --> ",12345,6789,1234"