I'm trying to loop over each line of output from a grep
and do something conditionally based on an interactive prompt.
I've looked at these: Iterating over each line of ls -l output
bash: nested interactive read within a loop that's also using read
Does bash support doing a read nested within a read loop?
But I'm still having trouble achieving what I want. I think the key difference is most of those examples are reading input from a file - I want to use a command. I've tried many variations of the following:
#! /bin/bash
function test1()
{
local out=$(grep -n -a --color=always "target" file.txt)
while read -u 3 line; do
echo -e "$line"
read -r -p "ok? " response
echo "you said: $response"
if [[ "$response" == 'n' ]]; then
return
fi
done 3<&0 <<< $out
}
function test2()
{
grep -n -a --color=always "target" file.txt | while read line; do
echo -e "$line"
read -r -p "ok? " response
echo "you said: $response"
if [[ "$response" == 'n' ]]; then
return
fi
done
}
In test1()
the FD redirection doesn't seem to do what I want. test2()
seems to just (unsurprisingly) stomp through my second read
. I assume this is because I need to switch up the FDs in use. I've tried to combine the FD redirection from test1
into test2
, but I haven't been able to get that to work with the pipe. I'm using bash version 4.4. What am I missing?
Here is an example run for the two functions above:
[~]$ cat file.txt
ksdjfklj target alsdfjaksjf alskdfj asdf asddd
alsdfjlkasjfklasj
asdf
asdfasdfs
target
assjlsadlkfjakls target
target aldkfjalsjdf
[~]$
[~]$ test1
you said: 1:ksdjfklj target alsdfjaksjf alskdfj asdf asddd 6:target 7:assjlsadlkfjakls target 8:target aldkfjalsjdf
you said:
you said:
you said:
you said:
^C
[~]$
[~]$
[~]$ test2
1:ksdjfklj target alsdfjaksjf alskdfj asdf asddd
you said: 6:target
7:assjlsadlkfjakls target
you said: 8:target aldkfjalsjdf
[~]$