Escaping the close-bracket character in a bash v3 heredoc -
i have need embed fragment of shell script in heredoc part of creation of cloud-init script provision ubuntu 14.04 lte machine. simplified version of script demonstrating problem follows:
#!/bin/bash cloudconfig=$(cat <<eof if host \$nameserver 1>/dev/null 2>&1; case \$reason in bound|renew|rebind|reboot) nsupdate -k /var/lib/dhcp/nsupdate.key << eox server \$nameserver update delete \$host_name update add \$host_name \$ttl \$host_addr send eox ;; esac fi eof ) echo "${cloudconfig}"
running above script fails follows:
little-net:orchestration minfrin$ bash /tmp/test.sh not read key /var/lib/dhcp/nsupdate.{private,key}: file not found couldn't address '$nameserver': not found
the problematic character closing bracket right of "reboot", , obvious solution escape character:
bound|renew|rebind|reboot\) nsupdate -k /var/lib/dhcp/nsupdate.key << eox
this backslash character ends in final cloudconfig variable, in turn breaks output:
little-net:orchestration minfrin$ bash /tmp/test.sh if host $nameserver 1>/dev/null 2>&1; case $reason in bound|renew|rebind|reboot\) nsupdate -k /var/lib/dhcp/nsupdate.key << eox server $nameserver update delete $host_name update add $host_name $ttl $host_addr send eox ;; esac fi
this particular fragment above part of larger file being written relies on variable interpolation, quoting there heredoc >>"eof" going break rest of our script.
how escape ")" character without escape character leaking through heredoc?
as seems bash 3.x parsing issue (as works in bash 4.x can seen here) need avoid parser getting confused. seems work me:
#!/bin/bash rp=")" cloudconfig=$(cat <<eof if host \$nameserver 1>/dev/null 2>&1; case \$reason in bound|renew|rebind|reboot${rp} nsupdate -k /var/lib/dhcp/nsupdate.key << eox server \$nameserver update delete \$host_name update add \$host_name \$ttl \$host_addr send eox ;; esac fi eof ) echo "${cloudconfig}"
Comments
Post a Comment