Skip to content

Instantly share code, notes, and snippets.

@kovetskiy
Created July 7, 2020 19:01
Show Gist options
  • Save kovetskiy/a4bb510595b3a6b17bfd1bd9ac8bb4a5 to your computer and use it in GitHub Desktop.
Save kovetskiy/a4bb510595b3a6b17bfd1bd9ac8bb4a5 to your computer and use it in GitHub Desktop.
#!/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.
help() {
sed -rn 's/^### ?//;T;p' "$0"
}
if [[ $# == 0 ]] || [[ "$1" == "-h" ]]; then
help
exit 1
fi
echo Hello World
@snejus
Copy link

snejus commented Oct 15, 2020

Why even use the extended version?

sed -n 's/^###//p' achieves the same. Just keep the leading ### format to the help only.

sed -n '/^###/ s///p' this one's faster but a tiny bit more verbose.

and sed '/^###/!d' if you don't mind hashes. Or grep "^###"

@ivant
Copy link

ivant commented Nov 29, 2023

My version, that doesn't require multiple # (but allows more than one if you want it for stylistic reasons):

#!/bin/bash
# Usage:
#   test_usage.sh ...

print_usage_and_exit() {
  # The sed script below:
  # - Deletes the first line (shebang).
  # - Quits on the first line that doesn't start with #.
  # - Removes the '#+ ?' prefix from the string.
  sed -En '1d; /^[^#]/ q; s/^#+ ?//p;' < "$0" >&2
  exit 1
}

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