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
  • 411,918
  • 54
  • 1,065
  • 1,164
sudoer
  • 33
  • 2
  • What shell are you using? (`echo $SHELL`) – Julie Pelletier Nov 02 '16 at 06:23
  • 2
    Why do you consider a space character to be non-printable? – techraf Nov 02 '16 at 06:39
  • I agree that it is printable but the `ls` command does normally treat it that way, at least `ls (GNU coreutils) 8.23` from bash. – Julie Pelletier Nov 02 '16 at 06:51
  • 1
    @JuliePelletier latest coreutils introduced an incompatible change to the way `ls` displays filenames. Several distributions have already reverted it but if yours hasn't you now need to include the `-N` flag. Everywhere. See [Why is 'ls' suddenly wrapping items with spaces in single quotes?](http://unix.stackexchange.com/questions/258679/why-is-ls-suddenly-wrapping-items-with-spaces-in-single-quotes) – roaima Nov 02 '16 at 08:16
  • @JuliePelletier I tried all kinds of shells including `bash sh csh ksh tcsh zsh`, so it should not be caused by the shells. I think @StephenKitt answered the question. – sudoer Nov 02 '16 at 20:07

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
  • 411,918
  • 54
  • 1,065
  • 1,164
  • 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