What's the best way to write cross-platform shell scripts

I have a shell script I would like to run on multiple platforms that support bash. My problem is that some commands behave differently on Linux, FreeBSD, OS X and Cygwin.

My thought so far:

  • Create a standard implementations of functions for all operations that are specific to the operating system, the main script, then check $OSTYPE

    and source

    the specific implementation of a file that (optional) replace commands that behave differently. And if I do that, how do I handle commands with multiple arguments? The four positional arguments passed to the function are not the cleanest approach.
  • Put all implementations in my script, each with an affix in the name, check $OSTYPE

    and create a variable OPSUFFIX

    , then call operation$OPSUFFIX

    for each operation.
  • ./configure

  • Go for something like Python - perhaps the most sensible, but require most code changes. And if it's an idiomatic init script, that's not an option.

source to share

1 answer

First, where possible, find ways to do what you want, where the differences won't matter. As an example, some versions of tar did not support the -z option to handle gzipped files. However, the combination of tar and gzip was portable. Likewise, there are ways to invoke ps that generally work on both BSD and LINUX.

Once you find that there are still things you need to deal with, your approach to finding a file to provide functions that handle command syntax seems to make sense. To avoid positional arguments, you can use getopt, which is a bash builtin.

An alternative might be to write a python script or similar, which simply encapsulates the worst of platfrom-dependent command behavior.



All Articles