web-dev-qa-db-ja.com

BASH-EOFタグ内の変数値を取得するにはどうすればよいですか?

私はこの次のスクリプトを持っていますが、EOFで始まりEOFで終わる各ブロック内で動作する$ i変数値を取得する必要があります.

変数値を読み取らず、$ iを置く

/var/tmp/vpn.sh私は持っています:

#!/bin/bash
amazonEth0="10.0.0.18"
amazonWan0="4.9.2.9"
vpnServer="4.8.8.6"
hosttoHost1="10.109.0.20/32"
hosttoHost2="10.109.0.21/32"
hosttoHost3="10.109.58.6/32"
hosttoHost4="10.109.59.3/32"

for i in 1 2 3 4
do
cat > /tmp/test$i.conf << \EOF
#Step 3
conn test"$i"
    #auto=start
    type=tunnel
    authby=secret
    pfs=no
    aggrmode=no
    ikelifetime=28800s
    lifetime=3600s
    ike=aes128-md5;modp1024!
    phase2alg=aes128-md5;modp1024
    forceencaps=yes
    left=$amazonLan0
    leftid=$amazonWan0
    leftsourceip=$amazonWan0
    right=$vpnServer
    rightsubnet=$hosttoHost$i
EOF
done

### Run me
cat > /var/tmp/vpn.sh << \EOF
service ipsec restart

######## Apply for loop here, instead of many many lines ###########
# for i in 1 2 3 4
# do
#   ipsec auto --add test$i
# done
ipsec auto --add test1
ipsec auto --add test2
ipsec auto --add test3
ipsec auto --add test4

######## Apply for loop here, instead of many many lines ###########
# for i in 1 2 3 4
# do
#   ipsec auto --up test$i
# done
ipsec auto --up test1
ipsec auto --up test2
ipsec auto --up test3
ipsec auto --up test4

ipsec auto --status
ip xfrm policy
ip route show

######## Apply for loop here, instead of many many lines ###########
# for i in 1 2 3 4
# do
#   ping -c 1 $hosttoHost$i
# done
ping -c 1 10.109.0.20; 
ping -c 1 10.109.0.21;
ping -c 1 10.109.58.6; 
ping -c 1 10.109.59.3; 

EOF
chmod +x /var/tmp/vpn.sh

# Cake - eat now - optional 
/var/tmp/vpn.sh > save output | mail -s ipsec date time &
22
YumYumYum

EOFの前のバックスラッシュを削除します。

#!/bin/bash

i=ok

# This prints "Bwah ok"
cat <<EOF
Bwah $i
EOF

# This prints "Bwah $i"
cat <<\EOF
Bwah $i
EOF

最終行を表示するにはrightsubnet="10.109.0.20/32"(i = 1の場合)、次のようなものが必要です。

i=1
val1=beep
val2=bop

rightval="val$i"
cat <<EOF
This is a beep: ${!rightval}
EOF

つまり、必要な変数の名前を計算し、別の変数に入れて、${!var}構文。

しかし、そのようなことには、むしろ配列を使用する必要があります。

i=0
vals=(beep bop)

cat <<EOF
This is a beep: ${vals[$i]}
EOF

ただし、インデックスは0から始まることに注意してください。

43
Pikrass