Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use single quotes inside awk statement that is surrounded by single quotes?

I'm having issues implementing this awk statement that I need for my script:

rsh fooDNS '
    ...

    BROADCAST_IP_ADDRESS=$(/usr/sbin/ifconfig $IF_NAME | grep broadcast |  awk '{print \$6}')
    ...
'

The issue here is that the statement above is contained within an rsh command surrounded by single quotations. Consequently, bash cannot interpret the single quotations around {print $6}, which is giving me a lot of problems. So far, I haven't been able to determine how to get around this issue.

like image 916
Justin Avatar asked Dec 15 '22 21:12

Justin


2 Answers

You can't nest single quotes, but you can end the single quoted string, include an escaped single quote, and then re-enter the quotes. Try this:

rsh fooDNS '
    ...

    BROADCAST_IP_ADDRESS=$(/usr/sbin/ifconfig $IF_NAME | grep broadcast |  awk '\''{print $6}'\'')
    ...
'

Nonetheless, this kind of quoting madness gets ugly very quickly. If at all possible, I recommend using scp/rcp/ftp to copy a normal bash script over to the remote and then run that. Failing that, I think you can use a trick like this if you don't need to feed anything to the script's stdin:

cat script_file | rsh fooDNS bash

(Use rsh fooDNS /bin/sh if your script is plain-sh-compatible and the remote side doesn't have bash, of course.)

As yet another alternative, if your snippet is short you can use here docs:

rsh fooDNS sh <<'EOF'
    ...
    BROADCAST_IP_ADDRESS=$(/usr/sbin/ifconfig $IF_NAME | grep broadcast |  awk '{print $6}')
    ...
EOF
like image 63
Walter Mundt Avatar answered Apr 09 '23 10:04

Walter Mundt


Replace the embedded single quotes by the sequence '\'' each time. In theory, you can just do:

rsh fooDNS '
    ...
    BROADCAST_IP_ADDRESS=$(/usr/sbin/ifconfig $IF_NAME | grep broadcast |
    awk '\''{print $6}'\'')
    ...
'

The first ' ends the current single quoted string; the \' sequence adds a single quote; the final ' restarts a new (but contiguous) single-quoted string. So, this introduces no spaces or anything.

On the other hand, it is best to avoid needing to do that. It is vulnerable to causing problems when the string is reinterpreted. And this is doubly the case when dealing with remote shells.

like image 45
Jonathan Leffler Avatar answered Apr 09 '23 12:04

Jonathan Leffler