diff --git a/src/unix/CCUnix.ml b/src/unix/CCUnix.ml index 7a9e9e02..6b0c1bfb 100644 --- a/src/unix/CCUnix.ml +++ b/src/unix/CCUnix.ml @@ -34,10 +34,12 @@ let finally_ f x ~h = raise e (* print a string, but escaped if required *) -let escape_str buf s = - if str_exists s +let escape_str s = + if + str_exists s (function ' ' | '"' | '\'' | '\n' | '\t'-> true | _ -> false) then ( + let buf = Buffer.create (String.length s) in Buffer.add_char buf '\''; String.iter (function @@ -45,7 +47,8 @@ let escape_str buf s = | c -> Buffer.add_char buf c ) s; Buffer.add_char buf '\''; - ) else Buffer.add_string buf s + Buffer.contents buf + ) else s let read_all ?(size=1024) ic = let buf = ref (Bytes.create size) in diff --git a/src/unix/CCUnix.mli b/src/unix/CCUnix.mli index 8bcf017c..90a6e47d 100644 --- a/src/unix/CCUnix.mli +++ b/src/unix/CCUnix.mli @@ -13,13 +13,13 @@ type 'a gen = unit -> 'a option (** {2 Calling Commands} *) -val escape_str : Buffer.t -> string -> unit +val escape_str : string -> string (** Escape a string so it can be a shell argument. *) (*$T - CCPrint.sprintf "%a" escape_str "foo" = "foo" - CCPrint.sprintf "%a" escape_str "foo bar" = "'foo bar'" - CCPrint.sprintf "%a" escape_str "fo'o b'ar" = "'fo'\\''o b'\\''ar'" + escape_str "foo" = "foo" + escape_str "foo bar" = "'foo bar'" + escape_str "fo'o b'ar" = "'fo'\\''o b'\\''ar'" *) type call_result = @@ -45,7 +45,7 @@ val call : ?bufsize:int -> (*$T (call ~stdin:(`Str "abc") "cat")#stdout = "abc" - (call "echo %a" escape_str "a'b'c")#stdout = "a'b'c\n" + (call "echo %s" (escape_str "a'b'c"))#stdout = "a'b'c\n" (call "echo %s" "a'b'c")#stdout = "abc\n" *)