To1ne
To1ne

Reputation: 1178

How to check the ls version

This topic is about the util 'ls' The BSD version uses the parameter '-G' to color up the output, while the Linux version uses parameter '--color'

Also the environment variable to set the colors is different: BSD: $LSCOLORS Linux: $LS_COLORS

But now the problem is: I want to determine which version is installed (using a small Shell script), so I can set alias ls and the environment appropriate in my .bachrc file.

Upvotes: 5

Views: 5528

Answers (5)

user5359531
user5359531

Reputation: 3555

combining the methods described, here's an easy way to use a bash function instead of an alias in order to make colors work regardless of if you are using BSD or GNU ls.

ll () {
  if ls --version &>/dev/null; then
    ls --color=auto -lahtr
  else
    ls -Glahtr
  fi
}

inspired by a particular conda env recipe pulling in GNU ls on my macOS system where my ls aliases were all hard-coded for stock BSD ls only.

Upvotes: 0

pixelbeat
pixelbeat

Reputation: 31728

As I mentioned above this seems to me to be the handiest method

if ls --color -d . >/dev/null 2>&1; then
    GNU_LS=1
elif ls -G -d . >/dev/null 2>&1; then
    BSD_LS=1
else
    SOLARIS_LS=1
fi

I've essentially this in my l script, which I use on various platforms to tweak ls output as I like

Upvotes: 6

martin clayton
martin clayton

Reputation: 78135

Just run 'ls' and see whether it throws an error, e.g. on my mac:

$ ls --color 1>/dev/null 2>&1
$ echo $?
1

Whereas

$ ls -G 1>/dev/null 2>&1
$ echo $?
0

Indicating -G is supported, but --color is not.

Upvotes: 4

Arthur Reutenauer
Arthur Reutenauer

Reputation: 2632

Ironically, the --version switch Kimmo mentions is not supported on most BSD systems :-)

Writing a portable configuration file for your particular setup can be a Herculean task. In your case, if you're sure your .bashrc is going to be used only on GNU/Linux and on a BSD system, you can check for switches that exist in one of the ls' but not in the other: for example, -D doesn't seem to be an accepted switch by ls on my BSD machines (FreeBSD and Mac OS X), whereas it is for GNU ls. Conversely, -P is accepted on BSD, but not on GNU/Linux. Knowing this, you can distinguish between the two ls' and set up environment variables accordingly.

Upvotes: 2

Kimmo Puputti
Kimmo Puputti

Reputation: 256

$ ls --version
ls (GNU coreutils) 6.10
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Richard Stallman and David MacKenzie.

Upvotes: 1

Related Questions