devsetup1-3 Exercise 2: A check-tools.sh Script ================================================= THE SCRIPT (save as check-tools.sh) ----------------------------------- #!/usr/bin/env bash # check-tools.sh CMD... # Report presence, path and first line of version output for each command. # Exit status is non-zero if any command is missing. missing=0 for cmd in "$@"; do if path=$(command -v "$cmd"); then ver=$("$cmd" --version 2>&1 | head -n 1) printf '%-10s FOUND %-22s %s\n' "$cmd" "$path" "$ver" else printf '%-10s MISSING\n' "$cmd" missing=1 fi done exit "$missing" RUNNING IT ---------- chmod +x check-tools.sh ./check-tools.sh git curl wget vim htop tree jq rg gpg lspci gcc make echo "exit status: $?" Expected: one FOUND line per tool and "exit status: 0" if the Chapter 2 starter tools are all installed. To see the failure path: ./check-tools.sh git nonexistent-tool echo "exit status: $?" which prints MISSING for nonexistent-tool and "exit status: 1". HOW IT WORKS ------------ - "if path=$(command -v "$cmd")" both tests for existence and captures the path in one step. command -v exits non-zero when the command is not found, so the if takes the else branch. - The version line uses --version and head -n 1 to keep output to one line. - 2>&1 is included because some tools print version text to standard error. - missing is set to 1 on any failure and used as the final exit status, so the script can be used in other scripts: ./check-tools.sh git || exit 1 KNOWN LIMITATIONS ----------------- - Not every tool understands --version. unzip and zip, for example, use -v, and may print usage text instead. The script will still report them as FOUND, because it tests existence first. - It checks commands, not packages. To check a package by name, use the pkg_installed function from the chapter. WHY THIS WORKS AS AN ANSWER --------------------------- It turns the check into something repeatable: the same one command can be run on devserver now and on a rebuilt machine later. Returning a proper exit status is what lets Chapter 10's provisioning script reuse it.