how to use if condition with sed command in BASH

Urgent help with bash scripting

1- i am using grep to find a string called: tinker panic 0 in a file /etc/ntp.conf
if the string is not there, i want to add the strings in /etc/ntp.conf file in the first line of the file. if not do nothing or exit.

2- also i want to add # in front of the following lines in /etc/ntp.conf only if # is not there.

Code:
#server 127.127.1.0 # local clock#fudge 127.127.1.0 stratum 10

Here what i have so far, but not working properly:

Code:
#!/bin/bash#const='tinker panic 0';if [ -e /etc/ntp.conf ] ; thenfound = 'grep "$const" /etc/ntp.conf' >/dev/null 2>&1 if [ "$found" -eq 0 ] ; then echo "not found" ; sed -i.bak '1 i\tinker panic 0' /etc/ntp.conf fifi
Thank you in advance.

This is a simple script that should do it for you:

#!/bin/bash
const='tinker panic 0'
if [ -e /etc/ntp.conf ]; then
  grep -q -e "$const" /etc/ntp.conf
  if [ $? = 1 ]; then
    echo "$const  ; not found but will be inserted as first line!"
    sed -i.bak '1 i\tinker panic 0' /etc/ntp.conf
  fi
fi
# Add '#' to beginning of line if it is not already there
sed -i.bak \
    -e 's/^server 127.127.1.0$/#server 127.127.1.0/' \
    -e 's/^local clock$/#local clock/' \
    -e 's/^fudge 127.127.1.0 stratum 10$/#fudge 127.127.1.0 stratum 10/' /etc/ntp.conf

hth

1 Like

Thank you very Much!