-4

I want to understand the use of shebang in an awk file named tool.

Suppose I have a shebang and make the file executable

#! /bin/awk -f

I can run the awk script with

tool file

or with

tool -v descriptor=1 file

Would it be possible to change FS, for instance

tool -v descriptor=1 FS="," file

Would I call tool the same way inside a bash script?

Would one be able to use

awk -f tool -v descriptor=1 file

within a bash script ?

Dilna
  • 405
  • 1
  • 6
  • 5
    what happens when you try it? – jhnc Feb 22 '23 at 22:13
  • I need a simple awk file for testing because what I currently have is too complicated. – Dilna Feb 22 '23 at 22:26
  • 2
    This topic is discussed at length in The Awk Programming Language (1988) (https://archive.org/download/pdfy-MgN0H1joIoDVoIC7/The_AWK_Programming_Language.pdf) e.g. Section 2.5 (p63) and Section 4.2 (p99) – jared_mamrot Feb 22 '23 at 23:09
  • 1
    Regarding `I need a simple awk file for testing because what I currently have is too complicated.` - if you know enough to create a complicated script, why can't you quickly and easily create a simple script? Anyway, here's one: `BEGIN{print "Hello World"}`. Also, don't use a shebang to call awk, see https://stackoverflow.com/a/61002754/1745001 as I've referred you to previously. – Ed Morton Feb 23 '23 at 00:04
  • Can the shebang difficulties be overcome? – Dilna Feb 23 '23 at 12:34
  • If you call from bash, the shebang is neglected. – Dilna Feb 23 '23 at 14:06

2 Answers2

1

Here's the standard syntax when calling awk with -f:

awk [-F sepstring] -f progfile [-f progfile]... [-v assignment]... [argument...]

Now, by using #!/bin/awk -f as shebang, the tool command will be exactly equivalent to:

/bin/awk -f tool

So it's possible to append other -f profile, -v assignment and file arguments to it; for example:

tool -F, -v descriptor=1 -v othervar=2 -- file1 file2

notes:

  • You can use -F, instead of -v FS=,
  • -- is for stopping the parsing of options.
Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • There seems to exist great dis-agreement between people who use a shebang and those who disapprove of it because of certain difficulties. – Dilna Feb 23 '23 at 12:34
  • 1
    @Goncho It seems to be the case. I personally don't even use `awk -f` in shell scripts because I prefer to be able to see the code that's executed. – Fravadona Feb 23 '23 at 13:37
0

I suggest taking look at following 2 snippets from awk man page

-f program-file

--file program-file

Read the AWK program source from the file program-file, instead of from the first command line argument. Multiple -f (or --file) options may be used.

and

-W exec file

--exec file

Similar to -f, however, this is option is the last one processed. This should be used with #! scripts, particularly for CGI applications, to avoid passing in options or source code (!) on the command line from a URL. This option disables command-line variable assignments.

Daweo
  • 31,313
  • 3
  • 12
  • 25