-   Linux - Newbie (
-   -   Trying to write a bash script need some suggesstions. (

ajaylinuxrk 05-29-2013 07:03 AM

Trying to write a bash script need some suggesstions.

I want to write a bash script to read a line by line from a file and execute in a command and redirect the output to a file.I am able to think through the below syntax but not sure how to redirect the output of the command to another file.Need suggestions.


for i in "cat /tmp/file"
command | grep "$i"


Thanks in Advance.

shivaa 05-29-2013 07:07 AM

Just try:

while read -r i
command | grep "$i" > /path/to/output.txt
done < /tmp/file

Use while+read instead of for loop for reading output from a file line by line. The > /path/to/output.txt part redirects output of the command into a file named /path/to/output.txt.

chrism01 05-29-2013 07:12 AM

Given that each cmd is tun separately, you probably want '>>' i.e. append, instead of > (output), which will overwrite the file.

Habitual 05-29-2013 11:11 AM


... stuff...
... stuff...
echo "" > "$REPORT" #truncates "$REPORT"
... stuff...
        do ec2-deregister $i >> "$REPORT" # appends output of each iteration into "$REPORT"

grail 05-29-2013 12:00 PM

A slight alternative to shivaa's example and allowing the incorporation of chrism01's suggestion:

while read -r line
    command | grep "$line"
done< /tmp/file > /path/to/output.txt

David the H. 05-30-2013 06:32 PM

If the "command" prints the same output every time, and you just want to capture all the matching lines from the file, then this would probably do you better:


command | grep -f /tmp/file > /path/to/output.txt

All times are GMT -5. The time now is 07:37 AM.