0

I want to create bash shell script which can - find string in file - then delete word - then restart service

I have tried this code

Restart.sh

#!/bin/sh
grep -q 'RestartServiceApache' /srv/www/config_apa
if [ $result -eq 1 ];
        then
                sed '/RestartServiceApache/d' "/srv/www/config_apa"
                /etc/init.d/httpd reload
fi

and my config_apa

Hello my name is nutnud.

#RestartServiceApache

This is all just a test file.

and the Error is

./Restart.sh: line 3: [: -eq: unary operator expected

I tried a lot of script and it doesn't work there is always an error like cannot grep or something

2 Answers 2

3

In the Bourne Shell, to see the exit code status you can use:

$?

It looks like grep should give a 0 status if it matched a line and a 1 status if it did not match (http://www.gnu.org/software/grep/manual/html_node/Exit-Status.html), so you want to match for exit code 0.

So you could do this:

  #!/bin/sh
  grep -q 'RestartServiceApache' /srv/www/config_apa
  if [ $? -eq 0 ];
       then
            sed '/RestartServiceApache/d' "/srv/www/config_apa"
            /etc/init.d/httpd reload
  fi

However, an easier way can be found in the following answer:

Can grep return true/false or are there alternative methods

 if grep -q PATTERN file.txt; then
     echo found 
 else
     echo not found 
 fi

Replace the "echo found" portion with your code to remove the line and restart the service.

0
0

With new GNU sed it can be done in one line

sed -i '/RestartServiceApache/{e\/etc/init.d/httpd reload
                               d}' /srv/www/config_apa

You must log in to answer this question.

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