Skip to content

Instantly share code, notes, and snippets.

@tcely
Last active January 12, 2023 19:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcely/cf1abacf82cc856096619d74ae836a31 to your computer and use it in GitHub Desktop.
Save tcely/cf1abacf82cc856096619d74ae836a31 to your computer and use it in GitHub Desktop.
A good portable awk shebang is not easy to find.
#!/usr/bin/awk -f
#!/usr/bin/awk -E
#
# If you have an awk version that doesn't support the -f flag,
# then you are just out of luck.
#
# If you just have no clue where awk will be, or you prefer to use -E,
# then you can try this bash snippet to launch awk for you.
#
# You might think the -E tests below are overly complex. You'd be wrong.
# I thank Apple for their wonderfully broken awk on Mac OS X.
# If you find a system, this doesn't work on please let me know!
#
# Copy the below line to the top of the file:
#!/usr/bin/env bash
#
# Inspired by: https://unix.stackexchange.com/a/97280
#
_src="${0}"
function exec_awk() {
_cmd="$(command -v awk)"
_awk_prog="/awk:/ && /option/ && /-E/ {exit 1;} {next}"
_flag="-$("$_cmd" -E /dev/null </dev/null 2>&1 | "$_cmd" "$_awk_prog" && echo 'E' || echo 'f')"
true bash#; exec "${_cmd:-false}" "${_flag}" "${_src}" "$@"; exit;
}
true {}#; set -e; exec_awk "$@"
# You place your awk program below this line and make sure this file has
# execute permissions.
@tcely
Copy link
Author

tcely commented Jan 12, 2023

The goal is to have awk run the content of the file without introducing additional dependencies. (Using bash is a fallback that's not preferred.)

As the comments say, if you already know where awk will be and/or which variant of awk will be used, and you don't care about supporting any unknown systems, then just write the shebang you need using that knowledge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment