On Thu, Sep 6, 2018, at 12:48, Eric Blake wrote:
> On 09/06/2018 04:40 AM, Joshua Phillips wrote:
> > Escape sequences don't work in single quotes:
> > 
> > $ echo 'hello\world'
> > hello\world
> > $ echo 'hello\'
> 
> Warning. Use of 'echo' and backslashes is non-portable.  There are two 
> classical behaviors:
> 1. backslashes are not special to echo unless you pass -e, so you also 
> have to have -n to elide a trailing newline (this is the behavior of 
> bash by default)
> 2. backslashes ARE special by default, so you don't need -e; and \c 
> exists to elide a trailing newline, so you don't need -n (this is the 
> behavior of dash by default, and the behavior required by POSIX; bash 
> can also be configured to run in this mode via 'set -o posix; shopt -s 
> xpg_echo')
> 
> > Which makes it surprising that double backslashes get converted to single 
> > backslashes:
> > 
> > $ echo 'hello\\world'
> > hello\world
> > 
> > Is this intended behaviour?
> 
> Yes.  dash is obeying the POSIX-mandated behavior, and interpreting \ 
> sequences by default. Since \w is not a known sequence, dash cheats and 
> outputs \ as-is instead of giving you an error (although an error would 
> be friendlier at reminding you that \ is active-by-default in dash). 
> But since \\ is a known sequence, it gets interpreted by echo.
> 
> > Bash behaves as I would have expected.
> 
> Rather, bash in its default mode does what you are used to, but violated 
> POSIX.  Bash in the mode that I mentioned above (set -o posix; shopt -s 
> xpg_echo) behaves like dash.
> 
> -- 
> Eric Blake, Principal Software Engineer
> Red Hat, Inc.           +1-919-301-3266
> Virtualization:  qemu.org | libvirt.org

Thank you very much for your explanation. I did not realise it was the "echo" 
built-in itself further interpreting the backslash sequences - I thought it was 
the shell passing just a single backslash to the echo command. Trying with 
/bin/echo produces the two backslashes I expected, so that makes perfect sense, 
thanks. I'll note well that "echo" is not a good command to use to test shell 
quoting!

Reply via email to