Search code examples
linuxbashawksusetee

I want to pipe an output to multiple files in bash


I looked up how to do it but don't understand how to use tee. It is a little confusing because I am using an output from awk. Here is what I have so far: (keep in mind that I am a beginner)

num1=2
num2=4

awk 'if (/'$num1'/ == /'$num2'/) 
     {
         print "Hello"
     } 
     else  
     {
         print "Goodbye" 

     }' | tee file1.txt file2.txt

I don't know why the output from awk is not being printed in the text files.


Solution

  • Use awk -v name=value option to pass shell variables to awk:

    num1=2
    num2=4
    awk -v n1=$num1 -v n2=$num2 'BEGIN {if (n1 == n2) print "hello"; else print "Goodbye"}' 
     | tee file1.txt
    

    To redirect output from awk itself:

    awk -v n1=$num1 -v n2=$num2 'BEGIN {
        if (n1 == n2) print "hello"; else print "Goodbye"}' > output.txt