Notes

Checking operating system in a bash script and installing different programs

Edit on GitHub


Bash Scripting
3 minutes

Because i have multiple machines and use both Ubuntu and macOS, I often need to alter my commands to account for differences in commands. For example, to get colorized output for the ls command, Ubuntu would use the --color flag while macOS will use the -G flag. -G in Ubuntu is for --no-group, i.e. don’t print group names in long listing format. And i don’t want to write two different files for Ubuntu and macOS, i want to be able to use the same .dotfiles on both systems.

You can do this with either $OSTYPE or uname -s.

$OSTYPE on Ubuntu 20.04 is linux-gnu and on macOS Big Sur it is darwin20.0

1# Flush DNS cache
2if [[ $OSTYPE == darwin* ]]; then
3  # works on macOS
4  alias flushdns='sudo dscacheutil -flushcache'
5elif [[ $OSTYPE == linux* ]]; then
6  # works on Ubuntu 18.04+
7  alias flushdns='sudo systemd-resolve --flush-caches'
8fi

uname -s prints the operating system name. Once you have that, you can use an if/esle or case statement on it

 1UNAME=$(uname -s | tr '[:upper:]' '[:lower:]')
 2
 3# example if/esle statement 1
 4if [[ $UNAME = darwin ]]; then
 5  echo "You are on macOS"
 6elif [[ $UNAME = linux ]]; then 
 7  echo "You are on Linux"
 8fi
 9
10# example if/esle statement 2
11[[ $UNAME = darwin ]] && echo "You are on macOS" || echo "You are on macOS"
12
13# example if/esle statement 3
14if [[ $UNAME = darwin ]]; then echo "You are on macOS"; else echo "You are on macOS"; fi
1# use -G (masOS) or --color (Ubuntu) to get colorized output for ls command
2if [[ $UNAME = darwin ]]; then ls -G ~; else ls --color ~; fi

I got this from Google’s install script from Firebase CLI, which adjusts the binary file you need to download based on whatever system you’re on

 1echo "-- Checking your machine type..."
 2
 3# Now we need to detect the platform we're running on (Linux / Mac / Other)
 4# so we can fetch the correct binary and place it in the correct location
 5# on the machine.
 6
 7# We use "tr" to translate the uppercase "uname" output into lowercase
 8UNAME=$(uname -s | tr '[:upper:]' '[:lower:]')
 9
10# Then we map the output to the names used on the Github releases page
11case "$UNAME" in
12    linux*)     MACHINE=linux;;
13    darwin*)    MACHINE=macos;;
14esac
15
16# If we never define the $MACHINE variable (because our platform is neither Mac
17# or Linux), then we can't finish our job, so just log out a helpful message
18# and close.
19if [ -z "$MACHINE" ]
20then
21    echo "Your operating system is not supported, if you think it should be please file a bug."
22    echo "https://github.com/firebase/firebase-tools/"
23    echo "-- All done!"
24
25    send_analytics_event "missing_platform_$UNAME"
26    exit 0
27fi