Przejdลบ do treล›ci

๐Ÿงช Cross-Platform Shell Script Testing

Writing truly portable shell scripts requires testing across various platforms and shells. Here's how to set up an effective testing environment.

๐Ÿงฉ Why Test Across Platforms?

Even small differences in tools (grep, sed, find) or shell behaviors can break scripts unexpectedly.

Common issues include: - GNU vs BSD utilities (especially on macOS) - Different parameter expansion support - Variants of test and [[]] - Default shell version differences


๐Ÿงช Methods for Testing

1. Docker Containers

Use containers with different base images:

Image OS Variant Default Shell
alpine BusyBox/Linux ash (POSIX)
ubuntu GNU/Linux dash/bash
debian GNU/Linux dash/bash
centos Red Hat/Linux bash
rockylinux Community RHEL bash

Example:

1
2
docker run -it --rm alpine sh
docker run -it --rm ubuntu bash

You can mount current directory and test directly inside:

1
docker run -v $(pwd):/scripts -it --rm alpine sh -c 'cd /scripts && ./myscript.sh'

2. Virtual Machines (Vagrant/VirtualBox)

Ideal for testing full OS behavior including init systems, filesystem permissions, service managers.

Create a Vagrantfile:

1
2
3
4
5
6
7
8
9
Vagrant.configure("2") do |config|
  config.vm.define "ubuntu" do |u|
    u.vm.box = "ubuntu/focal64"
  end

  config.vm.define "freebsd" do |f|
    f.vm.box = "freebsd/FreeBSD-13.1-RELEASE"
  end
end

Run:

1
2
vagrant up
vagrant ssh ubuntu

3. Cloud-Based Sandboxes

Quick online testing without local setup:

  • GitHub Codespaces
  • Gitpod.io
  • Repl.it (supports multiple shells)

Great for quick experiments and sharing reproducible test cases.


4. Using ShellCheck Locally

Install ShellCheck for static analysis:

1
2
3
4
5
6
7
8
# Ubuntu/Debian
sudo apt install shellcheck

# macOS
brew install shellcheck

# Usage
shellcheck myscript.sh

It catches common mistakes even before running the script.


  1. Write initial draft locally.
  2. Validate syntax with shellcheck.
  3. Run in Docker (alpine, ubuntu, debian).
  4. Optionally test on real hardware or VM.
  5. Commit only after verifying portability.

๐Ÿงช Bonus: Quick POSIX Compliance Check

Test your script against multiple POSIX-compliant shells:

1
2
3
4
for shell in sh dash posh mksh; do
    echo "Testing with $shell..."
    $shell myscript.sh || echo "Failed in $shell"
done

๐Ÿ‘‰ Now proceed to: Basics - Shell 101