1

When developing a shell script that should run on various unix/linux derivates, i sometimes have the problem that some tools have to be called in a different way compared to other systems. For example if the arguments are different. I wonder what's the best way to solve this.

Should i use uname to check for the operating system name and rely on this to execute the tool in different ways or are there any "better" ways, some kind of "ability" check for shell commands and tools?

The systems in question are for example Linux, Mac OS X, Solaris and Irix -- all quite different when it comes to abilities of tools and shell commands.

harald
  • 403
  • 2
  • 6
  • 19

4 Answers4

1

Ahh, shell script portability, fun!

Yeah, uname and checking $SHELL are the easiest way (and only portable way I can think of) to do this.

Dennis Kaarsemaker
  • 19,277
  • 2
  • 44
  • 70
0

the easiest way to see what distro you're on is to check /etc/issue

~$ cat /etc/issue
Debian GNU/Linux 6.0 \n \l

~$ cat /etc/issue
CentOS release 5.8 (Final)
Kernel \r on an \m

~$ cat /etc/issue
Ubuntu 12.04.2 LTS \n \l
JayBoCC2
  • 11
  • 1
  • As i could remember /etc/issue is an LSB standard, it will work with some linux disto only, not with other *nix – DukeLion Feb 10 '13 at 08:49
  • Also, how do you parse that output??? What if someone has done # clear > /etc/issue to clear the screen on each logout? – Chris Rees Jan 25 '17 at 12:17
0

You could use the facter tool which is part of Puppet (but can be used independently, if you don't have Puppet in your environment) to get basic facts about the target system.

For instance:

$ facter operatingsystem
CentOS

$ facter kernel kernelversion osfamily
kernel => Linux
kernelversion => 2.6.32
osfamily => RedHat

gem install facter should be sufficient to install it on any system with Ruby available, if it's not in your system packages already.

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
0

You are much better off writing portable code. Almost anything is achievable using plain POSIX, and then you won't need to worry about which utilities take which options.

Shell functions are always helpful when something useful isn't available, for example ls -A:

ls-A()
{
    ls -f ${1+"$@"} | sort | sed '1,2d'
}

Of course, this is very contrived, but much better than maintaining multiple sets of code for each operating system, and also supports OSes that you hadn't thought of;

case $OS in
GNU)
    # some bashisms
    ;;
FreeBSD)
    # some shisms
    ;;
*)
    # Oops, don't know what to do!
    ;;
esac
Chris Rees
  • 275
  • 1
  • 7