2

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?

  • What shell are you using? (echo $SHELL) – Julie Pelletier Nov 2 '16 at 6:23
  • 2
    Why do you consider a space character to be non-printable? – techraf Nov 2 '16 at 6: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 2 '16 at 6: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? – roaima Nov 2 '16 at 8: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 2 '16 at 20:07
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.

  • 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. – Wyatt8740 Nov 24 '17 at 7:08
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.