3

I want to print $Usage using printf into a bash script.

Usage="Usage: \n \   
\tjkl [-lbmcdxh] [-f filename]\n \  
\t\t[-h] \tThis usage text.\n \  
\t\t[-f filename] \t cat the specified file. \n \  
\t\t[-l] \tGo to application log directory with ls. \n \  
\t\t[-b] \tGo to application bin directory. \n \  
\t\t[-c] \tGo to application config directory.\n \  
\t\t[-m] \tGo to application log directory and more log file.\n \  
\t\t[-d] \tTurn on debug information.\n \  
\t\t[-x] \tTurn off debug information.\n"

How can I print it using printf?

I was thinking about using this:

printf "%s\n" $Usage

But it doesn't work.

fedorqui
  • 275,237
  • 103
  • 548
  • 598

2 Answers2

3

The key point here is the lack of double quotes. Once you add them, you are done! This is because the quotes enable the expansion.

$ printf "$Usage"
Usage: 
 \   
    jkl [-lbmcdxh] [-f filename]
 \  
        [-h]    This usage text.
 \  
        [-f filename]    cat the specified file. 
 \  
        [-l]    Go to application log directory with ls. 
 \  
        [-b]    Go to application bin directory. 
 \  
        [-c]    Go to application config directory.
 \  
        [-m]    Go to application log directory and more log file.
 \  
        [-d]    Turn on debug information.
 \  
        [-x]    Turn off debug information.

echo together with -e enables interpretation of backslash escapes, so this would also work:

echo -e "$Usage"

See the difference of quoting or not quoting in a simpler case:

$ printf "hello \nman\n"
hello 
man
$
$ printf hello \nman\n
hello$

Finally, you may want to have a good read to: Why is printf better than echo?.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Nice to read that! Note I ended up writing a broader version of Dodon's answer, since his was lacking detail and insight. – fedorqui Jan 29 '15 at 13:02
1

You can use:

printf "$Usage"

or

printf "%b" "$Usage"

From man 1 printf:

 %b     ARGUMENT as a string with `\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN

If using %b don't forget to add double quotes around the argument

Victor Dodon
  • 1,796
  • 3
  • 18
  • 27
  • the output is not neat: it shows `Gotoapplicationlogdirectorywithls.` instead of `Go to application log directory with ls.`. At least to me. – fedorqui Jan 29 '15 at 11:12
  • That was because I forgot to add the quotes around $Usage, I've edited my answer. – Victor Dodon Jan 29 '15 at 11:18
  • Ok then, `printf "$Usage"` suffices. Since you saw the issue being the double quotes, I suggest you to add it into your answer, because it's the issue here. – fedorqui Jan 29 '15 at 11:22