Quantcast
Viewing latest article 1
Browse Latest Browse All 5

Answer by Sudo Bash for Invoking a script, which has an awk shebang, with parameters (vars)

Unfortunately, this is not easy to solve in a portable way. The standard technique looks like this (substitute /usr/bin/awk for your awk path):

#!/usr/bin/awk -fBEGIN { if (!len) len = 1; end = start + len }{ for (i = start; i < end; i++) { print $1 } }

The hard-coded awk path and non-standard -f flag, makes this not portable across all *nixes. If you are only ever going to run your script on one machine, then this may work fine. However, to make a portable awk script, you will need to wrap it in a shell script. Here are two ways that you can do it in one file:

The first way is standard and easy to read:

#!/bin/shawk 'BEGIN { if (!len) len = 1; end = start + len }{ for (i = start; i < end; i++) { print $1 } }'"$@"

Unfortunately, this falls short in two key ways:

  1. If your awk script contains a ' character, you will need to type it like this: '"'"' to "escape" it.
  2. If you are using a text editor with syntax highlighting, you will not get your awk script properly highlighted.

Another solution, is to use sed to strip out the sh wrapper:

#!/bin/shexec awk "$(sed '1,2d'"$0")""$@"BEGIN { if (!len) len = 1; end = start + len }{ for (i = start; i < end; i++) { print $1 } }

This is something like a two line shabang header. It calls awk using the file from line 3 down as the script argument. This allows you to keep your pretty syntax highlighting and you can still use ' characters to your heart's content. The two downsides I see are:

  1. Arguably this is non-intuitive to read.
  2. If you are using a code linter, it may not like this.

Viewing latest article 1
Browse Latest Browse All 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>