Some setup scripts should behave differently on a physical box than in a VM or container: skip the disk spin down, skip SMART checks, skip setting the hardware clock.
Run it without options and it prints what it found:
systemd-detect-virt
systemd-detect-virt --container
systemd-detect-virt --vm
Inside a Docker container it prints docker. Other answers are names like kvm, vmware, microsoft, lxc or wsl, and none on bare metal. --container and --vm limit the check to one kind, which matters for a container running inside a VM.
For scripts, use the exit code with -q. It returns 0 when it detects virtualization and non-zero when it does not:
if systemd-detect-virt -q --vm; then
echo "in a VM, skipping smartctl"
else
smartctl -H /dev/sda
fi
In units you do not need the command at all; ConditionVirtualization= does the same check.
Detection relies on hints the hypervisor or container runtime leaves behind, such as CPU flags, DMI data and files like /.dockerenv. Unusual setups can hide or fake those hints, so I would not use it as a security check.
Further reading: systemd-detect-virt man page