Search code examples
shellunixawkkshnawk

accessing outer shell variables inside nawk in ksh


I am trying to access a shell variable inside a piped nawk. I have never done this before and was wondering if its possible.

Here is the command sbdadm list-lu contents:

Found 2 LU(s)

          GUID                    DATA SIZE           SOURCE

600144f029bf0a0000004e0484740052 107380964864 /dev/rdsk/c9d0s1 600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3

Here is my sample of my script :

DISK=/dev/rdsk/c9d0s3
sbdadm list-lu |nawk '/$DISK/ {print}'

NOTE: I know the " /$DISK/" syntax will not work since $ is part of a regex symbol. I need the right syntax if such a code is ever possible.

In addition,does awk spawn another shell? If so, is it possible that I can export this variable $DISK to that shell.


Solution

  • The problem is not that $ is part of RE syntax; it's that / is the RE delimiter. If you were just looking for c9d0s3, then using the proper quoting would do the trick:

    $ DISK=c9d0s3
    $ awk "/$DISK/ {print}" output
    600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3
    

    Explanation: if you use "" instead of '', then the shell variable would be expanded before handing the program to awk, so awk would see

    /c9d0s3/ {print}
    

    as its program. You can still search for a pattern with / in it, but it takes some shell quoting magic:

    $ DISK=/dev/rdsk/c9d0s3
    $ awk "{if (match(\$0, \"$DISK\")) print}" output
    600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3
    

    And no, awk does not spawn a subshell. Why would it? And why would you need one to pass a variable if you can just do it through the environment?