diff --git a/scripts/checkbashisms.pl b/scripts/checkbashisms.pl
index 471deda..cfc2a49 100755
--- a/scripts/checkbashisms.pl
+++ b/scripts/checkbashisms.pl
@@ -421,7 +421,7 @@ m/$LEADIN\.\s+(\"[^\"]+\"|\'[^\']+\'|\$\([^)]+\)+(?:\/[^\s;]+)?)\s*(\&|\||\d?>|<
 
             my $re = '(?<![\$\\\])\$\'[^\']+\'';
             if ($line =~ m/(.*)($re)/o) {
-                my $count = () = $1 =~ /(^|[^\\])\'/g;
+                my $count = count_quotes_at_current_level($1, q{'});
                 if ($count % 2 == 0) {
                     output_explanation($display_filename, $orig_line,
                         q<$'...' should be "$(printf '...')">);
@@ -450,7 +450,7 @@ m/$LEADIN\.\s+(\"[^\"]+\"|\'[^\']+\'|\$\([^)]+\)+(?:\/[^\s;]+)?)\s*(\&|\||\d?>|<
 
             $re = '(?<![\$\\\])\$\"[^\"]+\"';
             if ($line =~ m/(.*)($re)/o) {
-                my $count = () = $1 =~ /(^|[^\\])\"/g;
+                my $count = count_quotes_at_current_level($1, q{"});
                 if ($count % 2 == 0) {
                     output_explanation($display_filename, $orig_line,
                         q<$"foo" should be eval_gettext "foo">);
@@ -536,6 +536,42 @@ m/$LEADIN\.\s+(\"[^\"]+\"|\'[^\']+\'|\$\([^)]+\)+(?:\/[^\s;]+)?)\s*(\&|\||\d?>|<
 
 exit $status;
 
+# Count how often $quote occurs in $prefix at the current command
+# substitution level.  Entering a $(...) restarts the quoting
+# context, so a plain prefix-wide count misjudges lines such as
+#   "$(grep "$var$" file)"
+# where the trailing $ of a quoted string inside the substitution
+# is the tail of that string, not the start of a $"..." or $'...'
+# string.
+sub count_quotes_at_current_level {
+    my ($prefix, $quote) = @_;
+    my $count = 0;
+    my @saved;
+    my $i   = 0;
+    my $len = length $prefix;
+    while ($i < $len) {
+        my $c = substr($prefix, $i, 1);
+        if ($c eq '\\') {
+            $i += 2;
+            next;
+        }
+        if ($c eq '$' && $i + 1 < $len && substr($prefix, $i + 1, 1) eq '(') {
+            push @saved, $count;
+            $count = 0;
+            $i += 2;
+            next;
+        }
+        if ($c eq ')' && @saved) {
+            $count = pop @saved;
+            $i++;
+            next;
+        }
+        $count++ if $c eq $quote;
+        $i++;
+    }
+    return $count;
+}
+
 sub output_explanation {
     my ($filename, $line, $explanation) = @_;
 
diff --git a/test/bashisms/gettext.sh b/test/bashisms/gettext.sh
index ebaec32..a2ad0bb 100644
--- a/test/bashisms/gettext.sh
+++ b/test/bashisms/gettext.sh
@@ -3,3 +3,6 @@
 echo $"hello world -- BASHISM"
 
 echo "foo ' bar moo'$"
+
+matches="$(grep "lib" "$file" | grep "$major$" | wc -l)"
+echo "$(grep "^Package: ${pkg}$" DESCRIPTION)"
