2017-11-27 11 views
1

私は動的にipsetルールを生成する必要があります。ので、私はスクリプトを作成し、エラーが配列からURLを取得しようとしている。はbashで配列値を出力できません

#!/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 

そのが悪い代用としてこれをしてください修正する

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 

任意の提案をエラーが発生します

+0

あなたはbash'はもはや適切である 'データ操作のレベルに達しました:これはあなたのように使用するなど、間接的なパラメータ展開を使用するよりもわずかに優れ、より直感的な操作を提供します使用する。適切なデータ構造を持つ言語を選択してください。 – chepner

答えて

1

declare -nで宣言されたnamerefを使用できます。 ${urls[@]}${urls[0]}${urls[5]//a/b}など

#!/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 
+0

本当に有益な説明をありがとうございました。 – Sha

2

あなたは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 
関連する問題