1

I am making a simple shell script which will minimize the time I spend in searching all directories under a parent directory and grep some things inside some files. Here's my script.

#!/bin/sh
MainDir=/var/opt/database/1227-1239/

cd "$MainDir"

for dir in $(ls); do

grep -i "STAGE,te_start_seq Starting" "$dir"/his_file | tail -1 >> /home/xtee/sst-logs.out

if [ -f "$dir"/sysconfig.out];
then
    grep -A 1 "Drive Model" "$dir"/sysconfig.out | tail -1 >> /home/xtee/sst-logs.out
else
    grep -m 1 "Physical memory size" "$dir"/node0/setupsys.out | tail -1 >> /home/xtee/sst-logs.out
fi

done

The script is supposed to grep the string STAGE,te_start_seq Starting under the file his_file then dump it sst-logs.out which it does. My problem though is the part in the if statement. The script should check the current directory for sysconfig.out, grep drive model and dump it to sst-logs.out if it exists, otherwise, change directory to node0 then grep physical memory size from setupsys.out and dump it to sst-logs.out. My problem is, it seems the if then else statement seems not to work as it doesn`t dump any data at all but if i execute grep manually, i do have data.

What is wrong with my shell script? Is there any more efficient way in doing this?

2
  • Where's the recursion? Sep 28, 2012 at 5:23
  • I notice that you have for dir in $(ls);. You should never parse the output of ls, because it's impossible to do reliably and there's always a better way. Try this instead: for dir in *. Sep 29, 2012 at 6:01

1 Answer 1

0

There is at least one syntax error; you are missing a space before the ] of the if statement. The line should be

if [ -f "$dir"/sysconfig.out ] ;

Strange that your script does not report that. Do you run it from cron? Before you start your script automatically, first make it sure that it works correctly. Add echo statements to debug your program:

if [ -f "$dir/sysconfig.out" ] ; then
  echo "$dir/sysconfig.out present"
  echo running grep -A 1 "Drive Model" "$dir"/sysconfig.out
  grep -A 1 "Drive Model" "$dir"/sysconfig.out | tail -1 >> /home/xtee/sst-logs.out
else
  echo "$dir/sysconfig.out absent"
  echo running rep -m 1 "Physical memory size" "$dir"/node0/setupsys.out
  grep -m 1 "Physical memory size" "$dir"/node0/setupsys.out | tail -1 >> /home/xtee/sst-logs.out
fi
1
  • Hi January. Thanks for the reply. Right now I am running manually, but planning to run from a cron job later. I will try your solution and feedback if it's okay or not :)
    – Jude
    Oct 2, 2012 at 1:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .