tags:

views:

109

answers:

4

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.

+1  A: 
$ 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&gt;
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.
Kimmo Puputti
The version that ships with MacOSX doesn't support '--version' though
Jean Regisser
The lack of a version will tell you something too. I don't have access to my Mac OSX box at the moment but you could try a `strings | grep version` if you can't get it using 'ls --version'.
Epsilon Prime
+1  A: 

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.

Arthur Reutenauer
+3  A: 

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.

martin clayton
pixelbeat
Maybe a stupid remark, but doesn't this cause a lot of overhead when the current directory contains many, many files? Or it that where the option '-d' is for?
To1ne
@To1ne - not stupid, good call. You could insert a suitable arg - maybe the root directory? - that will be found, and is unlikely to be full of many files. Or you could create a temporary file and explicitly ls that (then remove it). Or you could use /dev/null as the arg. Agree that someting should be in there, rather than nothing.
martin clayton
To1ne
-d just lists the directory not its contents. So now we've 4 comments explaining that rather than it being looked up/tried.
pixelbeat
+1  A: 

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

pixelbeat