Is there a Terminal command to know the macOS installed but from an external hard drive or from macOS recovery?
The ProductVersion is stored within the SystemVersion.plist file in CoreServices. This can be read using defaults:

defaults read /System/Library/CoreServices/SystemVersion ProductVersion


When you're accessing the startup disk from another volume, you'll need to provide the full path to both defaults and /System:

/Volumes/Macintosh\ HD/usr/bin/defaults read /Volumes/Macintosh\ HD/usr/bin/System/Library/CoreServices/SystemVersion ProductVersion