0

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
  • Manipulating your live config is brittle and error-prone. Perhaps a better approach would be to regenerate it from a template file with some simple tool to fill in a few configuration parameters from a separate configuration file. – tripleee Mar 22 '22 at 11:16
  • Got the solution. Syntax of 'for loop' was incorrect. I had to change it to - for line in "${var1[@]}" – Surajsingh Pawar Mar 22 '22 at 12:03
  • You only need to create a template - like `main.cf.template` - with tagged fields you will modify later with your values eg: `mynetworks = ###MYNETWORKS###` ; thus, you will generate the `main.cf` from the template configuration file after overwriting the tagged fields via eg `sed`. Because Postfix uses a lot of parameters, 1st create the template from command line using the `postconf` utility (plz read its manpage), and see what parameters are relevant to you. `postconf -d` will generate default values, `postconf -e` will modify/edit current ones. – Valery S. Mar 22 '22 at 12:56

1 Answers1

0

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
Juranir Santos
  • 370
  • 2
  • 6