在 shell osascript 命令中的“”之间插入一个变量?
Insert a variable in-between ' ' in a shell osascript command?
我在 shell 脚本中使用 MacOS osascript
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
理想情况下,该命令将 osascript -e 'quit app "Calendar"'
作为可行解决方案的示例。但是,我似乎无法在 ' ' 引号之间插入变量。
有什么解决方法?
单引号的要点(反正是要点之一)是为了防止变量插值。听起来您真正想要的是一种将双引号放入字符串中的方法。有很多方法可以做到这一点。一个常见的是:
osascript -e "quit app \"$appname\""
尝试:
osascript -e 'quit app '"$APPNAME"
或者,如果 osascript
需要额外的双引号,请尝试:
osascript -e 'quit app "'"$APPNAME"'"'
尝试使用字符串插值动态构建脚本总是很脆弱。您应该将应用程序名称作为 参数 传递给 AppleScript,这样您就不必担心通过两级解释器转义任何字符。
APPNAME= # 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
无论APPNAME
的值是多少,您都在执行完全相同的脚本;唯一的区别是脚本接收的参数。
我在 shell 脚本中使用 MacOS osascript
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
理想情况下,该命令将 osascript -e 'quit app "Calendar"'
作为可行解决方案的示例。但是,我似乎无法在 ' ' 引号之间插入变量。
有什么解决方法?
单引号的要点(反正是要点之一)是为了防止变量插值。听起来您真正想要的是一种将双引号放入字符串中的方法。有很多方法可以做到这一点。一个常见的是:
osascript -e "quit app \"$appname\""
尝试:
osascript -e 'quit app '"$APPNAME"
或者,如果 osascript
需要额外的双引号,请尝试:
osascript -e 'quit app "'"$APPNAME"'"'
尝试使用字符串插值动态构建脚本总是很脆弱。您应该将应用程序名称作为 参数 传递给 AppleScript,这样您就不必担心通过两级解释器转义任何字符。
APPNAME= # 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
无论APPNAME
的值是多少,您都在执行完全相同的脚本;唯一的区别是脚本接收的参数。