Melab
Melab

Reputation: 2822

Getting printf to print escaped backslashes

Because I need to be able to print lines that may start with what would otherwise be treated as an option by echo, I devised a shell function that uses printf to print to the terminal. If I needed to print newlines or tabs, I learned that I have to use %b instead of %s because printf "%s" "\n" would print the literal \n to the screen. The function is defined as this:

my_echo () {
    printf "%b" "${1}"
}

Just recently, I found out that trying to print escaped escape sequences is more complicated than it normally is. The command printf "%b" "\\n" will print a newline. To print the literal for a newline, I have to use printf "%b" "\\\n", but using this requires recoding all of my other functions and scripts to handle this. Is there some way to get printf "%b" "\\n" or whatever to come out as the escaped escape sequence?

Upvotes: 4

Views: 4074

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

Answer: Literal

Quoting types matter. If you don't want backslashes to be interpreted before they get to your function, put them in single-quoted strings:

printf '%b' '\\n'

...prints, as you request, a single backslash followed by a n, with no trailing newline.


Answer: Best-Practice

Keep your escape sequences in your format strings, and out of your data. Thus:

my_echo() { printf '%s\n' "$*"; }
my_echo_n() { printf '%s' "$*"; }

is actually a closer equivalent to standard echo behavior: Printing only a newline can be done by just calling my_echo with no arguments; printing a literal can also be done by passing that literal around: my_echo_n $'\n' will print a literal newline without any %b involved.

Similarly, to include a literal tab:

my_echo $'hello\tworld'

or

my_echo "hello"$'\t'"world"

Upvotes: 5

Related Questions