When writing shell scripts, it's common to install dependencies before executing a command. However, running an install command every timeāeven when the dependency is already availableācan slow down your workflow. A better approach is to check if the command exists before attempting an installation. This simple optimization can make scripts more efficient and avoid unnecessary package installations.
Consider a script that installs jq, a popular command-line JSON processor, and then processes a JSON file:
brew install jq && jq . data.json
This script ensures that jq is installed before running it, but thereās a flaw: every time the script runs, brew install jq executesāeven if jq is already installed. While Homebrew might not reinstall jq if it's already present, the command still takes time to check the package status.
A more efficient approach is to check whether jq is installed before attempting to install it. Here's how you can do that:
command -v jq >/dev/null 2>&1 || brew install jq && jq . data.json
How it works:
command -v jqchecks ifjqis available in the system.>/dev/null 2>&1suppresses output and errors, preventing unnecessary messages.|| brew install jqonly runsbrew install jqif the previous check fails (meaningjqis not installed).&& jq . data.jsonensures thatjqruns only after itās confirmed to be installed.
This approach works for various package managers and commands. Hereās how you might use it with npm:
command -v eslint >/dev/null 2>&1 || npm install -g eslint && eslint src/
Or with pip for Python packages:
command -v black >/dev/null 2>&1 || pip install black && black .
By integrating this pattern into your shell scripts, you can improve efficiency while ensuring dependencies are installed only when necessary.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.