diff --git a/ghc/GHCi/UI.hs b/ghc/GHCi/UI.hs
index e3ebeaf2d23dac979e23d22d86c1450a523a4d71..c1fce215c3899c5438173f12700b8575d74f2490 100644
--- a/ghc/GHCi/UI.hs
+++ b/ghc/GHCi/UI.hs
@@ -2263,10 +2263,23 @@ quit _ = return True
 
 scriptCmd :: String -> InputT GHCi ()
 scriptCmd ws = do
-  case words ws of
+  case words' ws of
     [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"]'.
+-- Used to scan for file paths in 'scriptCmd'.
+words' :: String -> [String]
+words' s = case dropWhile isSpace s of
+  "" -> []
+  s' -> go id s'
+ where
+  go acc []                          = [acc []]
+  go acc ('\\' : c : cs) | isSpace c = go (acc . (c :)) cs
+  go acc (c : cs) | isSpace c = acc [] : words' cs
+                  | otherwise = go (acc . (c :)) cs
+
 runScript :: String    -- ^ filename
            -> InputT GHCi ()
 runScript filename = do
diff --git a/testsuite/tests/ghci/should_run/T18027 SPACE IN FILE NAME.script b/testsuite/tests/ghci/should_run/T18027 SPACE IN FILE NAME.script
new file mode 100644
index 0000000000000000000000000000000000000000..d81cc0710eb6cf9efd5b920a8453e1e07157b6cd
--- /dev/null
+++ b/testsuite/tests/ghci/should_run/T18027 SPACE IN FILE NAME.script	
@@ -0,0 +1 @@
+42
diff --git a/testsuite/tests/ghci/should_run/T18027.script b/testsuite/tests/ghci/should_run/T18027.script
new file mode 100644
index 0000000000000000000000000000000000000000..fd839d239278ee4d3d6a2b1c41f018e99d09dfa9
--- /dev/null
+++ b/testsuite/tests/ghci/should_run/T18027.script
@@ -0,0 +1 @@
+: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
new file mode 100644
index 0000000000000000000000000000000000000000..d81cc0710eb6cf9efd5b920a8453e1e07157b6cd
--- /dev/null
+++ b/testsuite/tests/ghci/should_run/T18027.stdout
@@ -0,0 +1 @@
+42
diff --git a/testsuite/tests/ghci/should_run/all.T b/testsuite/tests/ghci/should_run/all.T
index 4a629350a2ec3b83235d196695ef17dedf607586..6d39d5794c08f8cb23371d2a572ac43488e447ec 100644
--- a/testsuite/tests/ghci/should_run/all.T
+++ b/testsuite/tests/ghci/should_run/all.T
@@ -64,3 +64,4 @@ test('T15633b',
 
 test('T16096', just_ghci, ghci_script, ['T16096.script'])
 test('T507', just_ghci, ghci_script, ['T507.script'])
+test('T18027', just_ghci, ghci_script, ['T18027.script'])