0

the -e switch used with echo enables it to understand escape sequences as so:

[root@localhost~]#  echo -e 'hello\b\bhi'
helhi
[root@localhost~]# 

But, the escape sequences are seemingly skipped in the snippet below:

[root@localhost~]# echo -e 'hello\b\b'
hello
[root@localhost~]# 

Can anyone help understand the behavior of the above code snippet?

When the same code snippet above, is executed in conjugation with the '-n' switch, it works! (ofcourse, with the -n behaviour where it removes the linefeed)

[root@localhost~]# echo -n -e 'hello\b\b'
hel[root@localhost~]# 

Regards

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Marc88
  • 9
  • 2
    Why do you think the escape sequences are skipped in the second snippet? Are you expecting that the \b escape causes a backspace+delete rather than just a backspace (reposition cursor) ? – user4556274 Jun 13 '20 at 11:43
  • 2
    If you are on a UNIX certified platform, -e is printed as the first echo argument. – schily Jun 13 '20 at 11:58
  • 1
    @schily Even on a UNIX certified platform, that's evidently a bash prompt, not an sh prompt, so all bets are off. – Gilles 'SO- stop being evil' Jun 13 '20 at 12:01
  • On UNIX certified platforms, even bash is compiled in a way that makedit behave conformant. Check MacOS or Solaris... – schily Jun 13 '20 at 12:04
  • For the full story of -e see https://unix.stackexchange.com/q/65803/5132 and https://unix.stackexchange.com/q/55101/5132 . – JdeBP Jun 13 '20 at 15:57
  • And this question is almost the same as https://unix.stackexchange.com/q/414159/5132 from 2018. – JdeBP Jun 13 '20 at 16:13

1 Answers1

7

A backspace character (echo -e '\b') moves the cursor to the left, but does not change what is displayed. So echo -e 'hello\b\b' displays hello, putting the cursor at the end of the word, then moves the cursor left by two positions, and then (due to the newline added by echo without -n) moves the cursor to the beginning of the next line. This is visually indistinguishable from echo hello.

Watch it in action:

for c in h e l l o '\b' '\b' '\n'; do
  echo -e "$c"; sleep 1
done

P.S. Don't do this kind of experiment as root. Shooting yourself in the foot as root can hurt a lot more than on your regular account.

  • 1
    Also, for c in h e l l o '\b' '\b'; do echo -ne "$c"; sleep 1; done should be useful to notice why hel is obtained in the OP last experiment. – Quasímodo Jun 13 '20 at 12:22
  • 1
    Note that there is significant variation in the world as to what BS does at the left margin, and so the first sentence comes with qualifications in a detailed explanation. – JdeBP Jun 13 '20 at 16:12