Site Map - skip to main content

Hacker Public Radio

Your ideas, projects, opinions - podcasted.

New episodes every weekday Monday through Friday.
This page was generated by The HPR Robot at


hpr2864 :: One weird trick to add a --help option to your awk scripts

Klaatu demonstrates two ways to add a --help message to your awk scripts

<< First, < Previous, , Latest >>

Hosted by Klaatu on 2019-07-25 is flagged as Clean and is released under a CC-BY-SA license.
awk, option, help, arg. (Be the first).
The show is available on the Internet Archive at: https://archive.org/details/hpr2864

Listen in ogg, spx, or mp3 format. Play now:

Duration: 00:20:13

Learning Awk.

Episodes about using Awk, the text manipulation language. It comes in various forms called awk, nawk, mawk and gawk, but the standard version on Linux is GNU Awk (gawk). It's a programming language optimised for the manipulation of delimited text.

The first method is in Awk itself.


#!/usr/bin/awk -f
#
# USAGE EXAMPLE:
# echo the input of some var
# $ foo -v var=8
#

BEGIN {
    if (length(var) == 0) {
        printf "%s %s\n", ENVIRON["_"], "is a proof-of-concept help message";
        printf "%s\n", "Usage:";
        printf "%s\n", "------";
        printf "%s %s %s\n", "$", ENVIRON["_"], "-v var=NUM";
        printf "%s\n", "substitute NUM with the number you want echoed";
        exit
    }
    else {
        printf "%s %s\n", "You have entered ", var;
    }
}

The disadvantage to this is that it only provides a help message if no option is provided. If you actually type --help, then you get Awk's help message, which is not useful in this context.

The shell script wrapper method uses the shell to parse options, which are then passed to an embedded Awk script:


#!/bin/sh

if [ "${1}" = "--help" -o "${1}" = "-h" -o "${1}" = "" ]; then
    echo "This is a help message."
    exit
fi

/usr/bin/awk -v var="${1}" '

BEGIN {
printf "%s %s\n", "You provided", var;
}'

The disadvantage here is only that you're not just writing an Awk script, you're writing a shell script with embedded Awk. I can't think of a reason not to do it this way (even though in the script that served as the inspiration for this episode, I don't use this method).


Comments

Subscribe to the comments RSS feed.

Leave Comment

Note to Verbose Commenters
If you can't fit everything you want to say in the comment below then you really should record a response show instead.

Note to Spammers
All comments are moderated. All links are checked by humans. We strip out all html. Feel free to record a show about yourself, or your industry, or any other topic we may find interesting. We also check shows for spam :).

Provide feedback
Your Name/Handle:
Title:
Comment:
Anti Spam Question: What does the letter P in HPR stand for?
Are you a spammer?
What is the HOST_ID for the host of this show?
What does HPR mean to you?