Command substitution ($(cmd)
or `cmd`
(also ${ cmd;}
in ksh93)) stores the standard output of cmd
minus the trailing newline characters (unless that output contains NUL bytes in shells other than zsh
).
It does nothing special with backslash. The only characters it may mess-up with are the NUL character (and every character past the first NUL occurrence in some shells) and those trailing newline characters.
var=$(printf '%s\n\n\n' 'foo\bar\\baz')
Will store foo\bar\\baz
in $var
.
If you don't see those backslashes in $var
that would be either because you didn't check if they're there properly like by using an echo
or print
implementation that interprets backslash escape sequences.
For instance in UNIX conformance mode, bash
's echo
gives:
bash-4.3$ echo "$var"
foar\baz
(the \b
was expanded to a backspace character which when sent to a terminal makes it go backward one character).
You want to use printf
to output arbitrary data (and don't forget to quote your variables):
bash-4.3$ printf '%s\n' "$var"
foo\bar\\baz
And when that output goes to a terminal, you may want to post-process it with sed -n l
so control characters or trailing space characters for instance become visible.
Or it's because those backslashes were not output on stdout. For instance:
foo() {
printf foo
printf '\\' >&2
printf 'bar\n'
}
When running that function:
bash-4.3$ foo
foo\bar
bash-4.3$ var=$(foo)
\bash-4.3$ printf '%s\n' "$var"
foobar
The \
did not make it to $var
it was output to stderr.
Or of course it could be because they're not output at all as your comment to Benjo's answer suggests, but then that would be a problem in your java application, not bash
.
x=$(echo 'abc=\=abc'); echo $x
– choroba Sep 27 '16 at 08:34