0

I saw a video tutorial for the paste command, in which three files foo,bar,baz were connected horizontally with a "+" sign between.

cat foo
51
33
67

cat bar
10
1
13

cat baz
7
100
15

So, he used a paste command to make each line a whole addition and piped this into a while-loop which iterates through each line and puts it into the bc calculator:

paste -d+ foo bar baz | while read bla;do echo $bla|bc;done

I was confused why he used the complicated while-loop since

paste -d+ foo bar baz|bc 

worked as well,

however this made me thing "Are there situations in which piping into the while-loop makes sense or is even the only way to achieve something?"

2

In this case it was just for outputting what is progressed at the moment, and that line for line. Piping while loops is sometimes really useful e.g. displaying a progress bar. Progress Bar Example:

for i in $(seq 1 100)
do
sleep 0.1 
echo $i
done | whiptail --title 'Test script' --gauge 'Running...' 6 60 0
  • when I run your program, it looked as if the for loop piped for each iteration once into the whiptail command, this seems to be similar to xargs as it also pipes not once but many times....am i wrong? – sharkant May 27 '17 at 19:58
  • 1
    Yeah it pipes every time. Exactly that is, what makes it so useful. :) – ADDB May 27 '17 at 20:00
  • I did not know about it, but it is helpful to realize, however your for loop is on the left side of the pipe, does it make a difference ? – sharkant May 27 '17 at 20:08
  • Well it makes no difference. For that let me explain piping with a few words: Command 1 | Command that works with Output 1 | Command that works with Output 2 And with loops that command handles every sub-output of the loop. – ADDB May 27 '17 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.