Try this. Works happily in the latest release of Monterey and also in the current Public Betas.
The script checks if Xcode is installed currently, and if it is, exits cleanly. If Xcode is not present, then it performs a touch to deposit a file in /tmp and runs a grep, tail, and sed, to extract the current latest Xcode Command Line Tools name as a variable, then pumps that into softwareupdate to install it with verbosity.
#!/bin/zsh
echo "Checking Command Line Tools for Xcode"
# Only run if the tools are not installed yet
# To check that try to print the SDK path
xcode-select -p &> /dev/null
if [ $? -ne 0 ]; then
echo "Command Line Tools for Xcode not found. Installing from softwareupdate…"
# This temporary file prompts the 'softwareupdate' utility to list the Command Line Tools
touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress;
PROD=$(softwareupdate -l | grep "\*.*Command Line" | tail -n 1 | sed 's/^[^C]* //')
softwareupdate -i "$PROD" --verbose;
else
echo "Command Line Tools for Xcode have been installed."
fi
Topic:
App & System Services
SubTopic:
Core OS
Tags: