Home > Software design >  zsh variable substitution modifies surrounding string
zsh variable substitution modifies surrounding string

Time:01-18

Why does the "c" character go missing in the following example?

var="\bINSERT"
echo abc${var}def
> abINSERTdef

Is there any documentation that tells me how to do similar things or disable the behaviour?

I can't find any shell variables documentation.

CodePudding user response:

The command substitution isn't doing anything wrong -- it's echo whose behavior is surprising (legally; POSIX allows, but does not require, echo to interpret backslash escape sequences by default, so zsh is not in the wrong here).

printf '%s\n' abc${var}def

...doesn't have your problem (but for portability to non-zsh shells, I would quote "abc${var}def").

See Why is printf better than echo? on Unix & Linux Stack Exchange, and the POSIX spec for echo at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html

CodePudding user response:

As already was mentioned in the comments, the zsh implementation of the internal echo differs from the one implemented by the external echo command.

If you want to continue using echo, there are several workarounds:

  1. Do a echo -E ...; the -E turns off the backslash interpretation.
  2. Do a command echo ...; the keyword command forces the shell to use the external echo command.
  3. Set in the shell the option set bsd_echo and then just leave the echo command as it is. The option tells the shell to not use by default the backslash interpretation for its internal echo command.
  •  Tags:  
  • Related