Reputation: 166
I need to generate ipset rules dynamically. so i created following script and having error try to get the urls from array.
#!/bin/bash
# urlList
allow_SMTP_OUT_URLS=(mtp.sendgrid.net)
allow_HTTP_OUT_URLS=(archive.mariadb.org)
allow_HTTPS_OUT_URLS=(ppa.launchpad.net repo.mongodb.org www.google.com)
allow_SSH_OUT_URLS=(bitbucket.org)
ipsetNames=(allow_HTTP_OUT allow_HTTPS_OUT allow_SMTP_OUT allow_SSH_OUT)
for ipSET in "${ipsetNames[@]}"
do
ipset create -exist $ipSET hash:ip timeout 86400 comment family inet
chkIPSETexsit="$(ipset list -n | grep $ipSET)"
# Check / Adding IPSET rules
if [ -z "$chkIPSETexsit" ]; then
echo "$ipSET is empty"
exit 1
else
echo "$ipSET is present. Adding URLs to ipset"
urlList=$ipSET
urlList+="_URLS"
echo "urlList: $urlList"
echo URLs: ${(echo $urlList)[@]}
fi
done
its gives error as bad substitution
allow_HTTP_OUT is present. Adding URLs to ipset urlList: allow_HTTP_OUT_URLS /root/salt-cron-scripts/test2.sh: line 30: ${(echo $urlList)[@]}: bad substitution
Any suggestions to correct this please
Upvotes: 2
Views: 79
Reputation: 7499
You can use a nameref declared with declare -n
. This gives you a slightly better and more intuitive manipulation than using indirect parameter expansion, such as using: ${urls[@]}
, ${urls[0]}
, ${urls[5]//a/b}
etc.
#!/bin/bash
# urlList
allow_SMTP_OUT_URLS=(mtp.sendgrid.net)
allow_HTTP_OUT_URLS=(archive.mariadb.org)
allow_HTTPS_OUT_URLS=(ppa.launchpad.net repo.mongodb.org www.google.com)
allow_SSH_OUT_URLS=(bitbucket.org)
ipsetNames=(allow_HTTP_OUT allow_HTTPS_OUT allow_SMTP_OUT allow_SSH_OUT)
for ipSET in "${ipsetNames[@]}"
do
ipset create -exist $ipSET hash:ip timeout 86400 comment family inet
chkIPSETexsit="$(ipset list -n | grep $ipSET)"
# Check / Adding IPSET rules
if [ -z "$chkIPSETexsit" ]; then
echo "$ipSET is empty"
exit 1
else
echo "$ipSET is present. Adding URLs to ipset"
urlList=${ipSET}_URLS
echo "urlList: $urlList"
declare -n urls=$urlList
echo "URLs: ${urls[@]}"
fi
done
Upvotes: 2
Reputation: 530920
You need to use indirect parameter expansion to expand the array named by urlList
.
allow_SMTP_OUT_URLS=(mtp.sendgrid.net)
allow_HTTP_OUT_URLS=(archive.mariadb.org)
allow_HTTPS_OUT_URLS=(ppa.launchpad.net repo.mongodb.org www.google.com)
allow_SSH_OUT_URLS=(bitbucket.org)
ipsetNames=(allow_HTTP_OUT allow_HTTPS_OUT allow_SMTP_OUT allow_SSH_OUT)
for ipSET in "${ipsetNames[@]}"
do
ipset create -exist "$ipSET" hash:ip timeout 86400 comment family inet
chkIPSETexsit="$(ipset list -n | grep $ipSET)"
# Check / Adding IPSET rules
if [ -z "$chkIPSETexsit" ]; then
echo "$ipSET is empty"
exit 1
fi
echo "$ipSET is present. Adding URLs to ipset"
urlList=${ipSET}_URLS
echo "urlList: $urlList"
urlList=$urlList[@]
echo "URLs: ${!urlList}"
done
Upvotes: 2