I just came across a script that had a beautiful method of printing help messages. I am unsure why this method is not used more. Here is an example:


$ cat helpExample.sh
#!/bin/bash
usage()
{
echo "Usage: ${0##*/}
This is an example help message in BASH.
-x this option does nothing
" >&2
exit $1
}
usage 1

The script is using echo ” followed by a multi line help message redirected to standard error (" >&2). Output:


$ ./helpExample.sh
Usage: helpExample.sh
This is an example help message in BASH.
-x this option does nothing

2 Responses to “Printing pretty help/usage messages”

  1. admin Says:

    Here Documents would work equally as well.

  2. admin Says:


    Hi Brock,

    Can you please explain ${0##*/}
    $0 - prints the command name
    when i ran it with just $0 i got he following:
    Usage: ./testt.sh ( i named the script testt.sh)

    Yes $0 prints the command name. ${0#*/} removes everything up to the first forward slash in the command name. Here is an example:


    $ cat scriptName.sh
    #!/bin/bash
    echo '$0 ' = $0
    echo '${0#*/} ' = ${0#*/}
    echo '${0##*/} ' = ${0##*/}


    $ ./scriptName.sh
    $0 = ./scriptName.sh
    ${0#*/} = scriptName.sh
    ${0##*/} = scriptName.sh


    $ /home/noland/scriptName.sh
    $0 = /home/noland/scriptName.sh
    ${0#*/} = home/noland/scriptName.sh
    ${0##*/} = scriptName.sh

    Another resource is my 10 Steps to Beautiful Shell Scripts post.

    Thanks,
    Brock

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.