How to get error status back to bash from osascript
Here is a bit of a different approach that does not use System Events.  The following AppleScript code will get the name of the front most application, then that application will check to see if it has any open windows.  If that application does have an open window, it will be closed.  Also, for example, if the front application has an unsaved document as window 1, and you want to be prompted to save that document, just remove the "without saving" part of the command. 

This works for me using the latest version of macOS Mojave.

delay 5 -- GIVES TIME TO TEMPORARILY SET FOCUS ON ANY OPEN APP.. FOR TESTING PURPOSES
tell application "Finder" to set appName to name of (path to frontmost application)
tell application appName to if windows is not {} then close window 1 without saving