Shell Script – Avoiding BASH-isms in Shell Scripts

ashbashshellzsh

Does there exist a tool similar to Perl::Critic that will inspect your shell scripts and point out flaws, portability issues, uses of non-standard programs without fallbacks, depreciated program uses, etc?

I realize that set -o posix will disable non-POSIX usage, but that won't tell me things I want to know, such as zsh indexing shell arrays starting at 1, and bash, from 0, and ash not supporting arrays at all.

Best Answer

There's checkbashisms. On Debian, it's shipped as part of the package maintainer tools.

Test your scripts under dash and posh. Both have a few non-POSIX constructs, but if your script works in both, it's likely to work in most places. (With the caveat that it's difficult to test typical shell scripts as they tend to have a lot of corner cases.)

If you intend for your scripts to be portable to embedded Linux platforms, test them with BusyBox. Note that BusyBox can be more or less restricted, depending on how small an embedded system you want; it's quite normal to have scripts that rely on a feature that some BusyBox installations don't have.

Note that non-portability doesn't come from the shell alone, it also comes from external utilities. OpenBSD and Solaris tend to have utilities with POSIX features and not much more, so they're good for testing for portability.

You'll want to refer to the POSIX specification, and other resources mentioned in this thread (especially the autoconf manual); but that's documentation, it doesn't help if you use a feature accidentally.