shell 中嵌套的定界符

shell 中嵌套的定界符

如何让嵌套的heredocs在shell脚本中工作?它似乎无法识别 EOF。

#!/bin/bash

test(){

    cat > /users/shared/test.sh << EOF
#!/bin/bash

check_VPN_status(){
# Returns vpn_status as connected // disconnected

    anyconnect_status=$(/opt/cisco/anyconnect/bin/vpn status | grep 'Connected')
    globalprotect_status=$(ifconfig | grep -c flags=8050)

    if [[ ! -z $anyconnect_status \
        || $globalprotect_status == 0 && -d /Applications/GlobalProtect.app ]]; then
        vpn_status=connected
        else
        vpn_status=disconnected
    fi
}

create_pf_conf(){

# Set the network interface to be used
if="en0"

# Set ports to be allowed
allowed_ports="{22}"

cat > "$pfconf" << EOF

# Default Deny Policy
block in all

# Skip the loop back interface
set skip on lo0

# Allowed inbound ports
pass in quick on $if proto tcp to any port $allowed_ports keep state

EOF
}

#----------------------------------------------------------#
#                         Global Variables                 #
#----------------------------------------------------------#

pfconf="/var/client/pf.conf"

#----------------------------------------------------------#
#                         Start Workflow                   #
#----------------------------------------------------------#


# Check if firewall is enabled and enable if needed
enable_firewall

# Get VPN connection status
check_VPN_status

if [[ $vpn_status == "connected" ]]; then
    # If connected to VPN, create pf.conf and enable pf
    create_pf_conf
    /sbin/pfctl -e -f $pfconf
else
    # If disconnected from VPN, disable pf
    /sbin/pfctl -d
fi

}

    EOF

/bin/echo "hi"
test```

答案1

只需使用任何其他“标识符”而不是 EOF 作为外部定界符。


    cat > /users/shared/test.sh << ABC

    # ... inner heredoc using EOF goes here...

    ABC

请参阅文档:https://tldp.org/LDP/abs/html/here-docs.html

它说:“选择一个足够不寻常的限制字符串,它不会出现在命令列表中的任何位置并造成混乱。”

答案2

显然,您已经有几个相互嵌套的heredocs,因此您必须为每个文档提供一组唯一的命名EOF 标记分隔符。顺便说一句,它不需要被称为“EOF”,它可以是任何字符串,只要开头和结尾的字符串匹配并且所有结尾分隔符没有缩进(与代码中的最后一个分隔符不同)。

相关内容