bashawk

Escape dollar sign in a Bash script (which uses AWK)


I want to use AWK in my Bash script, and this line clearly doesn't work:

line="foo bar"
echo $line | awk '{print $1}'

How do I escape $1, so it doesn't get replaced with the first argument of the script?


Solution

  • Your script (with single quotes around the awk script) will work as expected:

    $ cat script-single
    #!/bin/bash
    line="foo bar"
    echo $line | awk '{print $1}'
    
    $ ./script-single test
    foo
    

    The following, however, will break (the script will output an empty line):

    $ cat script-double
    #!/bin/bash
    line="foo bar"
    echo $line | awk "{print $1}"
    
    $ ./script-double test
    ​
    

    Notice the double quotes around the awk program.

    Because the double quotes expand the $1 variable, the awk command will get the script {print test}, which prints the contents of the awk variable test (which is empty). Here's a script that shows that:

    $ cat script-var
    #!/bin/bash
    line="foo bar"
    echo $line | awk -v test=baz "{print $1}"
    
    $ ./script-var test
    baz
    

    Related reading: Bash Reference Manual - Quoting and Shell Expansions