I’m writing a script which should provide an option -h for help, when I try to write the help-message, I want to make it look more decent, like this:
print_help()
{
printf "Usage:
./prog -v version
-h help
-x ...."
}
And when I run the script, the help-message should be printed as I wrote it, like this:
Usage:
./prog -v version
-h help
-x ....
In C, I can concatenate 2 strings in two lines like this:
printf("Usage:\n"
"./prog -v version\n"
" -h help\n"
" -x ....\n");
these two lines will be concatenated together and then printed out.
I want to do pretty much the same thing in shell, and I tried printf and echo, seems cannot make it.
Any other advice?
I can think of 2 ways to do this
Method 1: Enclose the string you want to separate on multiple lines with single quotes instead of double quotes:
Output:
Explanation:
Note that everything inside single quotes:
bash(so you cannot use variables such as$varinside)echo(including escaped chars, unless you useecho -e)Method 2 – Updated for indented use inside a method: If you just have 1 long string that you’d like to break down into multiple lines in your code for better readability, you can use double quotes with the
\notation:Output:
Explanation:
The
\character, when used as the very last character of a line in shell script, means line continuation (i.e. think of it as “hey! there’s more stuff coming for this current command, don’t execute it yet until you’ve read all of it!”)Personally, I prefer the 2nd route because you can use
echo -eand escape chars (\n) for more fine-grained control over what exactly gets output =)