'How do I modify some values in the /etc/postfix/main.cf file using bash script? [duplicate]

I need to change some commented key value pairs in the file /etc/postfix/main.cf. Rather than changing the values i'm trying to append those key value pair at the bottom of the file, because this also works. So I've kept those key value pairs in a separate file and trying to fetch those pairs as a string in my code. But while fetching those pairs from the file, only the first string in code is getting fetched in the loop and not the later ones. I don't understand where i'm going wrong in the code. Here is my code -

file1=/root/conf.txt
file2=/etc/postfix/main.cf
IFS=$'\n'

var1=($(grep -E '^mynetworks|^myhostname.*com$|^inet_interface.*all$' $file1))

echo ${var1[0]}
echo ${var1[1]}
echo ${var1[2]}

for line in $var1
do
grep -q $line $file2

        if [ $? -eq 1 ]
        then
        echo "Strings are added to the target file!"
        echo $line >> $file2
        else
        echo "String already exist in the file!"
        fi
done

file content of the file 'conf.txt' -

mynetworks = 127.0.0.0/8, 168.100.189.0/28
myhostname = centos7.example.com
inet_interface = all

output I get at the end of main.cf-

mynetworks = 127.0.0.0/8, 168.100.189.0/28

Output I desire at the end of the main.cf-

mynetworks = 127.0.0.0/8, 168.100.189.0/28
myhostname = centos7.example.com
inet_interface = all


Solution 1:[1]

I think your problem in in var1 variable. Try something like this:

file1=/root/conf.txt
file2=/etc/postfix/main.cf
IFS=$'\n'

for line in $(grep -E '^mynetworks|^myhostname.*com$|^inet_interface.*all$' $file1 )
do
  grep -q $line $file2
    if [ $? -eq 1 ]
    then
    echo "Strings are added to the target file!"
    echo $line >> $file2
    else
    echo "String already exist in the file!"
    fi
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Juranir Santos