Detecting Your Bash Environment: Linux, macOS, WSL, or Git Bash?
When writing cross-platform shell scripts, one of the first headaches you’ll run into is:
“Where am I running this code?”
- Is it a native Linux box?
- A macOS machine with Apple’s ancient Bash?
- A Windows developer using Git Bash?
- Or maybe WSL1/WSL2?
Having a simple way to detect the environment can save you from subtle bugs and let you adapt your scripts automatically.
A Minimal Bash Function
Here’s a tiny function I wrote that prints the operating system and the Bash version in a clean one-liner:
#!/bin/bash
detect_environment() {
local kernel env bash_version
kernel="$(uname -s)"
bash_version="${BASH_VERSION%%(*}"
case "$kernel" in
Linux)
if grep -qi "microsoft" /proc/version 2>/dev/null; then
if uname -r | grep -qi "microsoft-standard"; then
env="WSL2"
else
env="WSL1"
fi
else
env="Linux"
fi
;;
Darwin)
env="macOS"
;;
MINGW*|MSYS*|CYGWIN*)
env="Git Bash"
;;
*)
env="Unknown"
;;
esac
echo "$env;bash $bash_version"
}
detect_environment
Example Outputs
Depending on where you run it, you might see:
Linux;bash 5.2.32
macOS;bash 3.2.57
Git Bash;bash 5.2.15
WSL1;bash 5.1.16
WSL2;bash 5.1.16
Notice how it distinguishes between WSL1 vs WSL2 (they have different kernel signatures) and reports the Bash version in a short format.
Why This Matters
If you build scripts that should run everywhere, you often need to tweak behavior:
- Linux vs macOS → package managers (
apt
vsbrew
) - Git Bash → Windows path quirks
- WSL1 vs WSL2 → networking and filesystem differences
By detecting the environment first, you can conditionally branch your script without breaking things.
Project & Source
The function lives in a small GitHub repo:
👉 kpatronas/whatos
Feel free to fork it, improve it, or drop it into your ~/.bashrc
.
✍️ That’s it — a simple, practical snippet that makes cross-platform scripting easier!