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?

  • 2
    brew install coreutils ... and then prepend /usr/local/Cellar/coreutils/*/libexec/gnubin to your PATH.
    – muru
    Commented Feb 3, 2017 at 4:57

2 Answers 2


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

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

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.

  • 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. Commented Feb 3, 2017 at 4: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
    Commented May 21, 2021 at 20:34

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .