iEFdev

Code, Computers & Random Junk

Adding a Simple “Show Help” to a Script

I had a script I was using the other day, and realized I missed to add a help section/function. Luckily I had put it in the header section of, so why not use that. smile

For a tiny script thats all it needs, and adding some help to the header section is great when you start read it.

So, a simple solution is to just cat the script, sed the lines and then exit.

# Help
[[ $1 == '-h' ]] && cat $0 | sed -n '9,12p' && exit 1;

With '9,12p' representing the start/end line.

Here it is in a dummy example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env bash
#
# foo
#
# Description: A foo script
#
# ------------------------------------------------------------
#
# Usage:
# foo /path/to/file.txt            1 file
# foo /path/to/{more,files}.txt    More files
# foo -h                           Show help
#

ERR=0;

# Help
[[ $1 == '-h' ]] && cat $0 | sed -n '9,12p' && exit 1;

#
# Rest of the script ...
#

exit ${ERR};

When using it:

[me@myhost] ~$ foo -h
# Usage:
#   foo /path/to/file.txt            1 file
#   foo /path/to/{more,files}.txt    More files
#   foo -h                           Show help

Happy hacking…

/Eric

Comments