[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Fascinating problem with bash



"Oliver Schneider" <Borbarad@gmxpro.net> writes:

>Both cases can occur in several places (outer while loop). Since the
>paths can contain blanks, I resorted to a "while read" loop because
>"for" simply would tokenize the file names more than desirable.

As soon as I read this paragraph I saw the problem. I confirmed it
looking at the code. It's a common problem.

This construct:

some_cmd | while read var ; do
    OTHER_VAR=...
done

will result in OTHER_VAR being unset at the completion of the loop. That
is because the while command is on the right-hand side of the pipe
meaning it runs in a subshell. At the end of the while loop, the
subshell exits and any vars it sets will go away with it.

Since your "some_cmd" is just an echo, a solution that will work for you
is:

while read var ; do
    OTHER_VAR=...
done <<"EOF"
$SCRIPTCONF
/etc/$SCRIPTCONF
EOF

This uses what is called a "here document". You can read more about it
in the bash man page if you need to.

If a here document is not sufficient ("some_cmd" is more complex), the
redirection <(some_cmd) can be used. It appears in the bash 3.2.39 man page.
It may not be in bash version 2.

while read var ; do
    OTHER_VAR=...
done <(some_cmd)

You may find that clearer than a here document.


Reply to: