On Thu, 29 Jun 2023 11:55:12 +0200
Sebastian Luhnburg <[email protected]> wrote:
> #!/usr/bin/env bash
>
> initial_password="\$abc&xyz"
> echo "initial password: " $initial_password
> printf -v password '%q' $initial_password
> echo "initial password with escaped characters: " $password
> bash << EOF
> echo "password in here document: " ${password@Q}
> /bin/bash -c "echo 'password in subshell in here document: ' ${password@Q}"
> EOF
While Dominique has already responded adequately, I have several things to add.
One is that you should quote the expansion of initial_password in your printf
statement to impede word splitting and pathname expansion. Another is that you
should not requote the string with %q then proceed to do so a second time by
using the ${param@Q} form of expansion. Instead, use one or the other.
Traversing multiple quoting layers is hard and I would suggest simply not doing
it, if it can be helped. That being said, you could get the results that you
expect by conveying password as a discrete argument to bash (which is not a
subshell, by the way). Below is an example.
#!/bin/bash
initial_password='$abc&xyz'
printf -v password %q "$initial_password"
bash <<EOF
echo "password in bash as a child:" $password
bash -c 'echo "password in bash as a grandchild: \$1"' bash $password
EOF
--
Kerin Millar