You do need to escape $
when it is used in a syntactically-valid environment variable name, regardless of whether or not it is set.
In the first case, $
is not followed by alphanumeric characters (it is followed by a space) and this is not a valid environment variable name – a variable must have at least one character in its name. Therefore, the $
is taken literally.
In the second case, $RECYCLE
is a valid environment variable name even though it has no value. Therefore, $RECYCLE.BIN
becomes .BIN
when the empty value is substituted.
Consider instead:
find /tmp/somefiles | grep 'PATTERN' | sed 's/\$/$$/g' > /tmp/files_to_backup