LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Feeding a while loop with a command output (https://www.linuxquestions.org/questions/linux-newbie-8/feeding-a-while-loop-with-a-command-output-876940/)

tripi 04-25-2011 06:20 AM

Feeding a while loop with a command output
 
Hello,

I am posting this just for the sake of curiosity. I am trying to feed a while loop structure with a command output, but using the bash built-in I get the error "ambiguous redirect":

Code:

while read line
do
 echo $line
done < $(sed 1d $file)

I have tried very different things like using backticks style:

Code:

done < `sed 1d $file`
but I obtained the same output. I finally came across this solution that worked out, but I don't really understand why. Maybe somebody can enlighten me:

Code:

done < <(sed 1d $file)
Thanks in advance

acid_kewpie 04-25-2011 06:24 AM

I pipe the data in...


sed 1d $file | while read line
do
....
done

however your command you're trying to redirect also makes no sense. because of the $() bit you're trying to *execute* the contents of the file, which I assume is not what you want to do, unless the output of sed is a single line which is a valid command in itself. In the last one you are not executing the output, although in all honesty I don't recognise that format of bash syntax, it does work, and off hand I don't see it reducing to anything else I recognise. I guess that the <() syntax is putting the output into a temporary file handle which can then be opened conventionally by the first redirect < operator, as ultimately the redirect should be a file, not data.

grail 04-25-2011 06:45 AM

The issue you are having is that there is command substitution, which is what you are using initially,
and then there is process substitution, which you have found you should have used.

To add to this, the solution presented by acid_kewpie does work, however, as piping the data in will create a subshell, any changes made to any variables
external to the loop will be lost once the loop exits. For example (from links provided):
Code:

i=0
sort list1 | while read line; do
  i=$(($i + 1))
  ...
done
echo "$i lines processed"  # FAILS


tripi 04-25-2011 06:47 AM

Uhmmm I see what you mean. I now understand why the first two option didn't work, thanks for the explanation.
I have found another structure that works. It has been introduced in Bash 2.0/3.0

Code:

while read line
do
 echo $line
done <<< "`sed 1d $file`"


grail 04-25-2011 07:14 AM

Yes the herestring works, but it is definitely not intended to be used in this way. Maybe this will help.


All times are GMT -5. The time now is 07:28 PM.