I was looking for a way to escape a variable containing format specifiers and special characters like quotes, backslashes and line breaks so that when passing it to print -P
it'll print out literally.
So essentially I want these two to print the same:
> cat file.txt
> my_var="$(cat file.txt)"
> print -P "${<magic>my_var}"
A good example file for test cases I used is this:
Backslash \
Double Backslash \\
Single Quote '
Double Quote "
-----------------------
Escaped Linebreak \n
-----------------------
Color codes: %F{red}not red%f
Variable expansion $SHELL
Closest I got is ${${(q+)my_var}//\%/%%}
though that has issues with quotes, linebreaks, backslashes and variable expansion:
$'Backslash Double Backslash \
Single Quote '
Double Quote "
-----------------------
Escaped Linebreak \n
-----------------------
Color codes: %F{red}not red%f
Variable expansion /usr/bin/zsh'
I am aware of printf '%s\n' "$my_var"
. However in practice there's a lot of actual formatting going on in the print -P
around the variable, so this isn't useful to me. Using print -P
around the variable and printf
for the actual variable sadly also doesn't work as there are cases where string manipulation is applied to the contents of the variable.