Issue
I am using a MacOS osascript
command in a shell script and I try to run the following command:
APPNAME=$@
if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
echo "Closing..."
osascript -e 'quit app $APPNAME'
else
echo "*** The app is not open"
fi
Ideally, the command would be osascript -e 'quit app "Calendar"'
as an example of a working solution. However, I can't seem to insert a variable in-between ' ' quotation marks.
What would be a workaround?
Solution
Trying to build a script dynamically using string interpolation is always fragile. You should pass the app name as an argument to the AppleScript, so that you don't have to worry about escaping any characters through two levels of interpreters.
APPNAME=$1 # The name should be passed as a single argument.
if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
echo "Closing..."
osascript -e 'on run argv' -e 'quit app (item 1 of argv)' -e 'end run' "$APPNAME"
else
echo "*** The app is not open"
fi
No matter what the value of APPNAME
is, you are executing the exact same script; the only difference is the argument that script receives.
Answered By - chepner Answer Checked By - Cary Denson (WPSolving Admin)