schemacs
schemacs

Reputation: 2891

awk in bash not working

Code below is the simple version, but also illustrates the problem.

Version does not work:

df | awk -f <(cat - <<-'EOD'
{
    if(                                                                                                                                                                                       
        $1 == "tmpfs" ) {
            print $0;
        }
}
EOD
)

Version does work:

df | awk -f <(cat - <<-'EOD'
{
    if( $1 == "tmpfs" ) {                                                                                                                                                                     
            print $0;
        }
}
EOD
)

the difference is how I place condition with if, the same line (works) or different lines (not working). The production version has four long conditions, So I have to place them on different lines to make the code more readable. Any one have came into this?

Upvotes: 1

Views: 275

Answers (2)

Ed Morton
Ed Morton

Reputation: 204558

@mbratch answered your question, but as an aside, your posted script:

df | awk -f <(cat - <<-'EOD'
{
    if( \
        $1 == "tmpfs" ) {
            print $0;
        }
    }
EOD
)

can/should be written as just this:

df | awk '$1 == "tmpfs"'

If you tell us what you're trying to do, we could probably help more.

Upvotes: 3

lurker
lurker

Reputation: 58324

Just use escapes for end of line for your long if statement:

df | awk -f <(cat - <<-'EOD'
{
    if ( \
        $1 == "tmpfs" ) {
            print $0;
        }
}
EOD
)

awk syntax evidently expects the if statement/expression to be on a single line. In Unix/Linux it's common to be able to use the backslash () as a line continuation character. So it will treat the above if ( \ and the following line as if they were all on the same line syntactically.

Upvotes: 4

Related Questions