[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Bug in bash read builtin, info from while read REPLY leaking into se
From: |
Greg Wooledge |
Subject: |
Re: Bug in bash read builtin, info from while read REPLY leaking into separate red -r -p "$1" command in function |
Date: |
Sat, 8 Feb 2025 12:08:10 -0500 |
User-agent: |
Mutt/1.10.1 (2018-07-13) |
On Sun, Feb 09, 2025 at 02:48:42 +1100, carlyle_moulton@optusnet.com.au wrote:
> I have a script to go through file names in the current directory,
> check whether they contain blanks and optionally replace blanks with
> underscores.
for f in *[[:space:]]*; do
read -r -p "Fix <$f>? " yn
if [[ $yn = [Yy]* ]]; then
mv -- "$f" "${f//[[:space:]]/_}"
fi
done
With that said, now let's find your original issue:
> The first step in the main program is:-
> ls -l >/tmp/$USER/tempfile1
> Then follows a while read REPLY; do # loop to read records from
> /tmp/$USER/tempfile1
> # The first record is discarded, from the remainder the File_Name is
> extracted and passed to a functionas a quoted string to function
> File_Contains_Blanks "$File_Name"
> # Global variable GRV_File_Contains_Blanks returns true if there is at
> least one blank
> # Function Get_Reply is called to get a Y or N answer preceded by a
> prompt using the read command
OK, I think you have something like this:
while read -r f; do
if [[ $f = *[[:space:]]* ]]; then
read -r -p "Fix <$f>? " yn
fi
...
done < mylistfile
Is that close enough?
The problem here is that you're trying to use standard input for two
different things at the same time: you've redirected it from mylistfile,
and you're also using it to read a response from the user's terminal.
The version that I wrote (for f in ...) will avoid this problem by not
redirecting stdin.
But if you need to do something like this in the future, you can use
a different file descriptor for the redirection:
while read -r -u3 f; do
...
read -r -p "Do it? " yn
...
done 3< somefile
This way, stdin is used only for the read command, and not also for the
input file redirection.