[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Two bash programming questions (fwd)

From: Bob Proulx
Subject: RE: Two bash programming questions (fwd)
Date: Sun, 10 Jun 2001 19:52:58 -0600

> $ rpm -qf `which echo`
> sh-utils-2.0-13

The 'which' command will always report external commands.  But the
shell has internal replacements for many external commands.  The
'echo' command is one of those that is typically an internal shell
command unless you force it otherwise.

  type echo
  echo is a shell builtin

However, in this case I believe the behavior will be the same for both
of them.

> Is it correct behaviour for "echo" that
>   echo -en "\\\b"
> prints out "\b" instead of a "\" which is erased by the subsequent
> backspace immediately?

Try this.

  echo echo -en "\\\b"

This prints "echo -en \\b".  Which shows the shell is interpreting the
quoted string.  And the command will, of course, interpret the string
too.  Which means you really need two sets of quotes for characters
that are special to both the shell and to the command, such as the \

Try this for what you want.

  echo -en "\\\\\b"

> Split it:
>   echo -en "\\" ; echo -en "\b"

As to why splitting this into two commands works it is because the
backslashes fall off of the end of the string.  An undefined
behavior.  In this case the choice was to print a literal backslash
instead of using it to quote something.

  $ echo echo -en "\\"
  echo -en \

What would your program print if it only saw a single \ and nothing
following it?  The authors chose to print a literal backslash
character.  But as soon as you add more characters to the end it is no
longer a single \ and is now seen as quoting the characters after it.

  $ echo echo -en "\\\b"
  echo -en \\b

Note that 'echo' is a troublesome command to use portably when trying
to avoid the newline or when trying to use metacharacters.  Some
shells require -e to turn on metacharacters and some will print the -e
itself.  Some shells want -n to avoid the newline and some want "\c"
at the end of the string.  This is inconvenient to program around in

For portable scripts I recommend that you avoid 'echo' when doing
either metacharacters or avoiding newline printing and use the POSIX
defined 'printf' command instead.  It is also built into most shells
and so the performance will be equivalent to echo.  But the interface
definition is portable to all POSIX systems.  And it is always
available in sh-utils as well so even if a shell did not provide it as
a built in it is available externally.  [I still use the traditonal
echo for everything else but metacharacters and newline avoidance.  It
is the traditional method of printing in shell scripts.]

Using printf your example would be:

  printf "\\\\\b"


reply via email to

[Prev in Thread] Current Thread [Next in Thread]