8

I run OS/X on my personal machine and Linux on my remote servers. (I could never afford an Xserve even back when they still made 'em.) I'd love to use the same .bashrc file for both and I want to have ls show me colors so I can identify executable files, directories, and the like.

But the GNU ls on Linux wants to see the --colors command line switch or it will refuse to show colors. Apple's (BSD?) ls prefers to see the export CLICOLORS=1 shell variable to tell it to show colors.

I'd do both, but the Apple ls barfs if it sees an unknown --colors switch.

Is there are good way in .bashrc for me to detect whether ls accepts a switch and then decide whether to alias it with --colors or not?

Brian
  • 235
  • 2
    brew install coreutils ... and then prepend /usr/local/Cellar/coreutils/*/libexec/gnubin to your PATH. – muru Feb 03 '17 at 04:57

2 Answers2

10

When you're trying to do something portably, test for features, not platforms:

if ls --help 2>&1 | grep -q -- --color
then
    alias ls='ls --color=auto -F'
else
    alias ls='ls -FG'
fi

Platform tests break when platforms change. macOS ships a mix of BSD and GNU userland tools today, but this mix is shifting over time towards a greater preponderance of BSD tools. So, a test for "macOS" today may fail tomorrow when Apple replaces a GNU tool you were depending on with its nearest BSD equivalent if you are relying on a feature the two implement differently. Feature tests more often keep working in the face of change.

As a bonus, you sometimes end up creating support for platforms you did not originally test against. The above script fragment should also do the right thing on Solaris and FreeBSD, for example.

(This is the philosophy behind GNU Autoconf, by the way, which is why a configure script written 10 years ago probably still works on a brand new system today.)

Modify the aliases to suit. I'm just showing the values I use on the macOS and Linux systems nearest to hand as I write this.

Warren Young
  • 72,032
  • 1
    That's a very interesting idea that I have never heard of before, but would have saved me a lot of pain over the years keeping various aliases up to date. Thanks. – Tim Kennedy Feb 03 '17 at 04:38
  • This was so annoying for me, thanks for the great fix. For some reason VSCode's Terminal on macos's ls was different than the macos terminal's ls .... – Quang Van May 21 '21 at 20:34
2

you can check if it's linux, and then set ls for it. ie:

export CLICOLORS=1
if uname -a | grep Linux >/dev/null; then
  # your linux ls stuff
fi
rsm
  • 264