Postgresql – How to insert multiple IP addresses in a pg_hba.conf file via unix shell script

postgresqlscriptingunix

I need to write some IP addresses to the pg_hba.conf file of my Postgresql, in order to allow remote access from those IP to my machine.

I have the following code in shell script to do that for a single IP address

#!/bin/bash

######## PostgreSQL Child Server Host or IP Address
serverhost=$1

######## PostgreSQL Child Server pg_hba.conf File Path
pghbapath=$2

######## Shell Script Command to write the data at the end of the    pg_hba.conf file
sed -i "$ a host    all all     $serverhost/32  md5" $pghbapath

An example command to execute the above bash script is

./reset_ip.sh 192.168.10.27 /root/Desktop/BashScripts/pg_hba.conf

The above is working fine, but I have a lot of IP addresses with me. So, instead of manually running the command each and every time for a different IP address, is there a command which can take multiple IP addresses at once and write them to the pg_hba.conf file in one go?

Edit – Thanks a lot for the answer Luuk. I tried it and it worked. Now, suppose if instead of having a text file to hold all the address, I want to write the multiple IP addresses separated by commas in the command line itself, somewhat like

./reset_ip.sh 192.168.10.27,192.168.10.28,192.168.10.29,192.168.10.30 /root/Desktop/BashScripts/pg_hba.conf

Is it possible? What I basically want is to be able to pass multiple values for a single variable via the command prompt.

Best Answer

If you have a file which holds all the addresses (1 at a line) you can do:

cat ipaddresses.txt | while read line; 
do 
  ./reset_ip.sh $line /root/Desktop/BashScripts/pg_hba.conf; 
done

or, with gawk:

gawk '{ system("./reset_ip.sh $1 /root/Desktop/BashScripts/pg_hba.conf") }' ipaddresses.txt