BASH
Check and Install Missing CLI Tools
Create a robust Bash script to check for the presence of command-line tools and conditionally install them if they are not found, enhancing environment setup.
#!/bin/bash
check_and_install() {
local cmd=$1
local pkg=$2
if ! command -v "$cmd" &> /dev/null
then
echo "$cmd could not be found, attempting to install $pkg..."
# Example for Debian/Ubuntu
sudo apt-get update && sudo apt-get install -y "$pkg"
# Add more package managers as needed (e.g., yum, brew, apt install, dnf, pacman)
else
echo "$cmd is already installed."
fi
}
# Example usage:
check_and_install "jq" "jq"
check_and_install "node" "nodejs"
check_and_install "npm" "npm"
How it works: The `check_and_install` function takes a command name and its package name. It uses `command -v "$cmd"` to check if the command exists in the system's PATH. If not, it prints a message and attempts to install the package using `sudo apt-get` (assuming a Debian/Ubuntu system). This pattern is crucial for reliable development environment setup scripts.