While using printf how to escape special characters in shell script?
For the benefit of people who got here by clicking on the first search result after Googling "bash printf escaped", the correct way to use printf to generate bash-escaped text is:
printf " %q" "here is" "a few\n" "tests"
Which outputs (without a trailing newline):
here\ is a\ few\\n tests
Try
printf "%s\n" "$string"
See printf(1)
You can use $' '
to enclose the newlines and tab characters, then a plain echo
will suffice:
#!/bin/bash
get_lines() {
local string
string+='The path to K:\Users\ca, this is good'
string+=$'\n'
string+='The second line'
string+=$'\t'
string+='123'
string+=$'\n'
string+='It also has to be 100% nice than %99'
echo "$string"
}
get_lines
I have also made a couple of other minor changes to your script. As well as making your FUNCTION_NAME lowercase, I have also used the more widely compatible function syntax. In this case, there's not a great deal of advantage (as $' '
strings are a bash extension anyway) but there's no reason to use the function func()
syntax as far as I'm aware. Also, the scope of string
may as well be local to the function in which it is used, so I changed that too.
Output:
The path to K:\Users\ca, this is good
The second line 123
It also has to be 100% nice than %99
May I remark that "man printf" shows clearly that a "%" character has to escaped by means of another "%" so printf "%%" results in a single "%"