aircraft
aircraft

Reputation: 26924

Why the `\b` do not work when it as the last character in echo?

When I test bash script on my Mac, you know the \b is the DEL function:

$ echo -e "\\  2\b"
\  2
$ echo -e "\\  2\b123"
\  123
$ echo -e "\\  2\b "
\   

I found if the \b as the last character it will not work, see the first case. But if there is space or other character following it, it will work.


EDIT

Sorry, \b not DEL, it is backspace, thanks @Evert

Upvotes: 3

Views: 1092

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 125918

\b does not represent DEL, it represents backspace. This moves the Terminal cursor backward one space, but does not do anything to the character that's been backspaced over. If you print something after the backspace character, that'll be written over the previous character (effectively deleting it), but if you don't, it just remains on screen. If you want to really delete the character, send backspace+space+backspace (i.e. "\b \b").

BTW, echo isn't a good way to print sequences like this. Some versions convert escape sequences to the characters they represent, but some just print the escapes literally. I had to rewrite a bunch of my scripts when Mac OS X v10.5 came out, and had different behavior than I expected. Since then, I've always preferred printf for anything nontrivial. It's a bit more complicated than echo, because the first argument is treated as a format string, which is used to control how the rest of its arguments are printed. Also, it doesn't automatically add a newline at the end like echo does, so if you want that, you have to add it manually (with \n).

Finally, I'd use single-quotes for strings like this that include escape sequences, because in double-quotes some escape sequences get interpreted by the shell before being sent to the command (whether it's echo or printf). So here's how I'd do your second example:

printf '\\  2\b123\n'

Upvotes: 7

Related Questions