anvd
anvd

Reputation: 4047

awk script header: #!/bin/bash or #!/bin/awk -f?

In an awk file, e.g example.awk, should the header be #!/bin/bash or #!/bin/awk -f?

The reason for my question is that if I try this command in the console I receive the correct file.txt with "line of text":

 awk 'BEGIN {print "line of text"}' >> file.txt

but if i try execute the following file with ./example.awk:

#! /bin/awk -f
awk 'BEGIN {print "line of text"}' >> file.txt

it returns an error:

$ ./awk-usage.awk
awk: ./awk-usage.awk:3: awk 'BEGIN {print "line of text"}' >> file.txt
awk: ./awk-usage.awk:3:     ^ invalid char ''' in expression

If I change the header to #!/bin/bash or #!/bin/sh it works.

What is my error? What is the reason of that?

Upvotes: 4

Views: 12196

Answers (2)

moinudin
moinudin

Reputation: 138317

Since you explicitly run the awk command, you should use #!/bin/bash. You can use #!/bin/awk if you remove the awk command and include only the awk program (e.g. BEGIN {print "line of text"}), but then you need to append to file using awk syntax (print ... >> file).

awk -f takes a file containing the awk script, so that is completely wrong here.

Upvotes: 7

Residuum
Residuum

Reputation: 12064

Your script is a shell script that happens to contains an awk command.

#! /bin/sh tells your shell to execute the file as a shell command with /bin/sh - and it is a shell command. If you replace that with #! /bin/awk -f then the file is executed with awk, basically the same as executing

/bin/awk -f awk 'BEGIN {print "line of text"}' >> file.txt 

Upvotes: 2

Related Questions