Re: Fascinating problem with bash



"Oliver Schneider" <Borbarad@xxxxxxxxxx> 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.


--
To UNSUBSCRIBE, email to debian-user-REQUEST@xxxxxxxxxxxxxxxx
with a subject of "unsubscribe". Trouble? Contact listmaster@xxxxxxxxxxxxxxxx
Archive: http://lists.debian.org/6da1.4c7305f1.3cab7@xxxxxxxxxxxxxxxx



Relevant Pages

  • Re: Fascinating problem with bash
    ... some_cmd | while read var; ... will result in OTHER_VAR being unset at the completion of the loop. ... subshell exits and any vars it sets will go away with it. ... To UNSUBSCRIBE, email to debian-user-REQUEST@xxxxxxxxxxxxxxxx ...
    (Debian-User)
  • Re: Awesome Tutorials for JavaScript beginners
    ... If the statement is false we exit from the while loop. ... Most Web developers think browser scripting is ... var UA = navigator.userAgent.toLowerCase; ... I suppose they could contact the authors of the script ...
    (comp.lang.javascript)
  • Re: slowing a script down
    ... When I add an alert to check it for each step of the loop, ... var stringWidth = new String; ... panelwidth = the character position where the string px is first found? ... can be re-used to animate any panel. ...
    (microsoft.public.scripting.jscript)
  • Re: OT: posix sh problem
    ... foo | IFS= while read var ... I want to read some text from a pipe and process it word-by-word and act on the words in a loop ... You don't need those vars when the loop ends. ...
    (freebsd-questions)
  • Re: OT: posix sh problem
    ... foo | IFS= while read var ... I want to read some text from a pipe and process it word-by-word and act on the words in a loop ... You don't need those vars when the loop ends. ...
    (freebsd-questions)