Hi,
On 04/10/2023 09:47, Дилян Палаузов wrote:
Hello,
I want to print C:\abc in a portable way. Or rather, store the value
C:\abc in a variable. I have bash 5.2.15-3.fc38 and dash 0.5.12-1.fc38.
/bin/sh is a symlink to bash.
In interactive bash
echo "C:\\abc"
prints
C:\abc . The same happens when I store in a file and execute it:
#!/bin/bash
echo "C:\\abc"
#!/bin/bash --posix
echo "C:\\abc"
#!/bin/sh
echo "C:\\abc"
With dash it is different:
#!/bin/dash
echo "C:\\abc"
prints C:bc . When I replace above a with k, echo "C:\\kbc" prints
C:\kbc .
In dash, backslash acts as an escape character within echo. In bash, it
is configurable, it can either act as an escape character the same way
by default, or it can limit escape sequence processing to when the -e
option is used. In bash, the behaviour can be changed via
shopt -s xpg_echo and shopt -u xpg_echo. The default varies between systems.
When I replace the double quotes with single quotes, echo 'C:\\abc' ,
dash prints C:\abc, but bash (interactive, /bin/sh and bash --posix)
prints C:\\abc .
With shopt -s xpg_echo, this also prints C:\abc in bash. Note that this
configuration option is independent of POSIX mode, as POSIX allows
either behaviour.
To print a variable literally, without special treatment of backslash,
use the printf builtin instead.
printf "%s\n" "$var"
will output exactly the string that is stored in $var. If it contains
backslashes, this will print backslashes. And this works the same way in
dash and bash.
All that said I think this is a bug in dash.
The above echos are simplified use case, in reality I want to execute
A="C:\\abc" ./script and the script shall see C:\abc as value to the
variable A.
What you have there already achieves that. The special handling of
backslash in the echo command is specific to the echo command. For
passing environment variables to other processes, nothing special
happens (at least, nothing special that relates to backslashes).
Kind regards
Dilyan
Cheers,
Harald van Dijk