1832976 Members
2823 Online
110048 Solutions
New Discussion

Shell Script issue.

 
SOLVED
Go to solution
Gulam Mohiuddin
Regular Advisor

Shell Script issue.

I am trying to search hostname from a error file and writing it into the log.out file but some how this script doesnâ t write anything to log.out file, it just stays empty.

for varname in $(cat /opt/omni/lbin/hosts.lst)
do
grep -i $varname /tmp/fail.out > log.out
done

Thank
Everyday Learning.
6 REPLIES 6
Sridhar Bhaskarla
Honored Contributor

Re: Shell Script issue.

Hi Gulam,

Try ">>" instead of ">" in the third line.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Hoefnix
Honored Contributor

Re: Shell Script issue.

try:

cat /opt/omni/lbin/hosts.lst | while read varname
do
grep -i $varname /tmp/fail.out >> log.out
done



Regards

Peter
A. Clay Stephenson
Acclaimed Contributor

Re: Shell Script issue.

Your problem is that you are over-writing the output file so the last one wins. If the last ${varname} doesn't produce output then you get a null file.

rm -f log.out
for varname in $(cat /opt/omni/lbin/hosts.lst)
do
grep -i "${varname}" /tmp/fail.out >> log.out
done

That should fix you.
If it ain't broke, I can fix that.
Bill Hassell
Honored Contributor
Solution

Re: Shell Script issue.

Run the script in debug mode to see what is actually happening:

#!/usr/bin/sh
set -x
for varname in $(cat /opt/omni/lbin/hosts.lst)
do
grep -i $varname /tmp/fail.out > log.out
done

Or you can run the script using this syntax:

sh -x your_script

If the list of hosts is very long, use more to slow it down and 2>&1 to re-route the trace information to stdout:

sh -x your_script 2>&2 | more


Bill Hassell, sysadmin
Patrick Wallek
Honored Contributor

Re: Shell Script issue.

The way you have this running, it will always echo something to the log.out file, even if it is a null when the grep doesn't match anything.

I would consider something like this:

#!/usr/bin/sh
rm log.out

for varname in $(cat /opt/omni/lbin/hosts.lst)
do
HOST=$(grep -i ${varname} /tmp/fail.out)
if [[ ${HOST} != "" ]] ; then
echo $HOST >> log.out
fi
done

The above will do the grep and assign the result to HOST. Then if $HOST is NOT EMPTY it will write the value to log.out. Note the >> in the echo. That will append to the log.out file so that you get all possible results. If you still want to use your own script you can replace your > with >> but your log.out file may have some blank lines it when the grep doesn't return anything.
Jeroen Peereboom
Honored Contributor

Re: Shell Script issue.

By the way one can also write:
....
done > log.out
(or done >> log.out).
This is especially interesting if there is more than 1 command in the for-loop.

JP