The recommended pattern for bash as far as I know is to always quote the shell variables.
E.g. "$VAR"
instead of $VAR
.
But how can I achieve the same safety the quotes provide for variables meant to be interpreted remotely?
E.g in the following:
ssh server.com<<CODE
TARGET="target dir"
COUNT= \$( ls /foo/bar/\$TARGET | wc -l )
echo \$COUNT > count.txt
CODE
For the code to work I need to escape $COUNT
and $TARGET
.
But how do I achieve the same safety that the "$COUNT" or "$TARGET" provides for this specific case?
Update
I have pasted only the part that is problematic.
I have also other lines that the variables are defined outside of the heredoc so if I use <<'CODE'
then the snippet breaks.
For a more complete example:
SOME_STRING="SOME VALUE"
ssh server.com<<CODE
echo $SOME_VALUE > test_file.txt # <--- does not work if I use <<'CODE'
TARGET="target dir"
COUNT= \$( ls /foo/bar/\$TARGET | wc -l )
echo \$COUNT > count.txt
CODE