Reputation: 315
I wrote my usage function for a bash script using printf
, however, it was so cumbersome that I imagine there must be an easier way than the way that I did it. I am curious to find out what it is, so I can improve for next time (only 2 args shown below to illustrate the point).
Here is the code itself:
usage(){
printf "\n\e[1m%s\x1b[0m %-5s\n" "USAGE:" "Blah Blah"
printf "%7s \e[1m%-15s\x1b[0m %s %s\n" "" "-h" "[Optional]" "Display usage information"
printf "%7s \e[1m%-15s\x1b[0m %s %s" "" "-ofps" "[Optional] Number of output frames per second"
printf "%-34s %s\n" "" "Applies to the *output* video frame rate."
exit 1
}
Output looks like:
USAGE: Blah Blah
-h [Optional] Display usage information
-ofps [Optional] Number of output frames per second
Applies to the *output* video frame rate.
If there was a way of specifying that the string in the rightmost "column" should wrap around (and preserve the indent) if the length of the entire line were to exceed 80 characters that would be the functionality I am looking for.
I am interested in pure bash solutions, but particularly, I am interested the most in the easiest way to do this while still using printf
.
Upvotes: 4
Views: 1723
Reputation: 1642
This is the way I typically do my Usage commands, it doesn't use printf, but it is effective. (I also use tput instead of raw escape sequences. Check the tput(1)
and terminfo(5)
manual pages for details)
Usage="Blah Blah [-options...]
options
$(tput bold)-h$(tput sgr0) Display usage information
$(tput bold)-o<fps>$(tput sgr0) Number of output frames per second
Applies to the *output* video frame rate
"
Then, whenever I want to print it, I put:
echo 2>&1 "?Usage: $Usage";
exit 1
or some variation. If you want to, you can add | fmt
to the end of the echo. That will do the word-wrapping for you. But typically, I just do the big multi-line string at the start of my script, just after the #!/bin/env bash
to act as internal documentation as well as the usage message.
Upvotes: 4