diff --git a/ghc/GHCi/UI.hs b/ghc/GHCi/UI.hs
index c1fce215c3899c5438173f12700b8575d74f2490..36e27dd5b46a757be046aa66b8596093a00aab43 100644
--- a/ghc/GHCi/UI.hs
+++ b/ghc/GHCi/UI.hs
@@ -2267,12 +2267,15 @@ scriptCmd ws = do
     [s]    -> runScript s
     _      -> throwGhcException (CmdLineError "syntax:  :script <filename>")
 
--- | A version of 'words' that does not break on backslash-escaped spaces.
--- E.g., 'words\' "lorem\\ ipsum dolor"' yields '["lorem ipsum", "dolor"]'.
+-- | A version of 'words' that treats sequences enclosed in double quotes as
+-- single words and that does not break on backslash-escaped spaces.
+-- E.g., 'words\' "\"lorem ipsum\" dolor"' and 'words\' "lorem\\ ipsum dolor"'
+-- yield '["lorem ipsum", "dolor"]'.
 -- Used to scan for file paths in 'scriptCmd'.
 words' :: String -> [String]
 words' s = case dropWhile isSpace s of
   "" -> []
+  s'@('\"' : _) | [(w, s'')] <- reads s' -> w : words' s''
   s' -> go id s'
  where
   go acc []                          = [acc []]
diff --git a/testsuite/tests/ghci/should_run/T18027.script b/testsuite/tests/ghci/should_run/T18027.script
index fd839d239278ee4d3d6a2b1c41f018e99d09dfa9..bb13844f817e45b0e303880baed55dc214463e54 100644
--- a/testsuite/tests/ghci/should_run/T18027.script
+++ b/testsuite/tests/ghci/should_run/T18027.script
@@ -1 +1,2 @@
 :script T18027\ SPACE\ IN\ FILE\ NAME.script
+:script "T18027 SPACE IN FILE NAME.script"
diff --git a/testsuite/tests/ghci/should_run/T18027.stdout b/testsuite/tests/ghci/should_run/T18027.stdout
index d81cc0710eb6cf9efd5b920a8453e1e07157b6cd..daaac9e303029e7a028c253092d148af7da57483 100644
--- a/testsuite/tests/ghci/should_run/T18027.stdout
+++ b/testsuite/tests/ghci/should_run/T18027.stdout
@@ -1 +1,2 @@
 42
+42