2

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.

2
  • How many times are you going to use this script? if an address is added to pg_hba.conf it is added, and does not need to be added again?
    – Luuk
    Nov 2, 2019 at 10:54
  • @Luuk What i mean is, I have around 200 IP addresses. Now instead of running the script separately 200 times for each of the IPs, is it possible to take all of them in one command and run it once?
    – suvrat
    Nov 2, 2019 at 11:07

1 Answer 1

2

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.