3

ls -b should print the file names with non-printable characters, for example, ex ex.txt should be shown as ex\ ex.txt, but this does not work on macOS, it is still ex ex.txt. Does anyone know the reason?

Stephen Kitt
  • 434,908
sudoer
  • 33

1 Answers1

3

The -b option isn't standardised, so its behaviour is implementation-dependent.

Many Linux systems use GNU ls by default; it defines the -b option as

print C-style escapes for nongraphic characters

and uses an elaborate quoting implementation. The space character is a nongraphic character so it ends up being escaped.

On macOS the definition of -b is different:

-B Force printing of non-printable characters (as defined by ctype(3) and current locale settings) in file names as \xxx, where xxx is the numeric value of the character in octal.

-b As -B, but use C escape codes whenever possible.

The ctype functions (or macros) consider that the space character is printable, so it's not escaped.

Stephen Kitt
  • 434,908
  • A way to mimic the behaviour of Coreutils ls -b would likely be ls -b | sed 's/ /\\ /g'. I don't have a mac to test this at the moment. This would catch spaces, at least, but I don't know about other characters. – Wyatt Ward Nov 24 '17 at 07:08
  • 1
    That would work in some cases, but post-processing the ls output is touchy in general because you can’t distinguish between file names and the rest of ls’s output. – Stephen Kitt Nov 24 '17 at 10:21