15

Help Message for Shell Scripts

 3 years ago
source link: https://samizdat.dev/help-message-for-shell-scripts/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Have you ever thought how good it would be to have a help message for your shell script that you wrote a month ago and already forgot what it is supposed to do?

Yeah, there is always a way to show a message using cat (meow) or a bunch of echo calls.

But there is a neat trick.

Add your message with all the required information on top of your file, just right after the shebang.

#!/bin/bash
###
### my-script — does one thing well
###
### Usage:
###   my-script <input> <output>
###
### Options:
###   <input>   Input file to read.
###   <output>  Output file to write. Use '-' for stdout.
###   -h        Show this message.

Halfway done, now need to get this message in runtime with sed.

help() {
    sed -rn 's/^### ?//;T;p' "$0"
}

$0 means a filename of a file that is being executed.

A bit about the magic that is going here:

s
/
^### ?
//
T
p

Now just call the help function if an arg -h or no args passed.

if [[ $# == 0 ]] || [[ "$1" == "-h" ]]; then
    help
    exit 1
fi

Hope it helps, cheers!

Full gist is available on GitHub: https://gist.github.com/kovetskiy/a4bb510595b3a6b17bfd1bd9ac8bb4a5


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK