MacOS – Error when using “do shell script”

applescriptmacos

I'm using a MacBook Pro (Retina, Mid-2014) running El Capitan. I'm trying to create a script that checks if my computer is open or not, and I'm using this:

ioreg -r -k AppleClamshellState | grep '"AppleClamshellState"' | cut -f2 -d"=""

I tested this in Terminal and it works fine, so I add do shell script in front of it to run it in AppleScript. But when I do, it gives me this:

Expected end of line, etc. but found identifier.

Please help!

Best Answer

Instead of piping to grep and cut, just use awk.

do shell script "ioreg -r -k AppleClamshellState | awk -F \" = \" '/AppleClamshellState/ {print $2}'"
  • -F \" = \" makes the separator: = (space = space)
  • /AppleClamshellState/ Search for: AppleClamshellState
  • {print $2} Prints Yes or No depending on what's returned for:AppleClamshellState
  • E.g "AppleClamshellState" = No prints No

enter image description here

You can also use:

do shell script "ioreg -r -k AppleClamshellState | grep 'AppleClamshellState' | cut -d'=' -f2"

However there will be a leading space in front of Yes or No as cut only handles a single character for the deliminator.

enter image description here

Note: The command text portion of do shell script, e.g. do shell script "uptime" must be double-quoted. So when the command text string itself is using double-quotes within the string, one should substitute a single-quote ' wherever possible and if double-quotes must be used within the string then escape them with a backslash \.