Sunday, February 7, 2021

Bash: Easy help print

Ok, lets create a single line of bash that will handle the -h option and print something.

First, what to print? I usually add some comments on the start of the file, so lets print that. Example script:

#  This is the doc of the script

the line that we will add

code of script

Lets go step by step. We need to print the file it self:

cat "$0"

Skip the first line (lets switch to sed):

sed -n '2,$ p' "$0"

Go until you find the first empty line:

sed -n '2,/^$/ p' "$0"

Remove the # fro the start of the line:

sed '2,/^$/ s/#// p' "$0"

Finally, we check if the -h is the first argument, print the thing and exit:

[ "$1" = '-h' ] && sed -n '2,/^$/ s/#// p' "$0" && exit