The code below use a font-lock rule with a function instead of a regexp, the function search for occurrences of
$VAR but only when they are inside a double-quoted string. The function
(syntax-ppss) is used to determine this.
The font-lock rule use the
prepend flag to add itself on top of the existing string highlighting. (Note that many packages use
t for this. Unfortunately, this overwrites all aspects of the existing highlighting. For example, using
prepend will retain a string background color (if there is one) while replacing the foreground color.)
(defun sh-script-extra-font-lock-is-in-double-quoted-string ()
"Non-nil if point in inside a double-quoted string."
(let ((state (syntax-ppss)))
(eq (nth 3 state) ?\")))
(defun sh-script-extra-font-lock-match-var-in-double-quoted-string (limit)
"Search for variables in double-quoted strings."
(and (setq res
(2 font-lock-variable-name-face prepend))))
(defun sh-script-extra-font-lock-activate ()
(font-lock-add-keywords nil sh-script-extra-font-lock-keywords)
(if (fboundp 'font-lock-flush)
You can call use this by adding the last function to a suitable hook, for example:
(add-hook 'sh-mode-hook 'sh-script-extra-font-lock-activate)