我正在尝试编写一个运行profiles -P
的安装检查脚本,并根据响应退出。
我们使用来自meraki的配置文件,输出看起来如此(如果已安装):
_computerlevel[1] attribute: profileIdentifier: com.meraki.sm.mdm
There are 1 configuration profiles installed
有没有办法检查这个确切的响应?
我在想这样的事情:
#!/bin/bash
output=profiles -P
if [ output = com.meraki.sm.mdm ]; then
exit 0;
else
exit 1;
有什么想法吗?
答案 0 :(得分:0)
尝试以下方法:
#!/bin/bash
if sudo profiles -P | egrep -q ': com.meraki.sm.mdm$'; then
exit 0
else
exit 1
fi
sudo profiles -P
的输出(请注意profiles
始终需要root权限)通过管道(|
)发送到egrep
;这两个命令形成一个管道。egrep -q ': com.meraki.sm.mdm$'
搜索profile
的输出:
-q
(安静)选项不会产生任何输出,只需通过退出代码发出是否找到匹配(0
)或1
)的信号。': com.meraki.sm.mdm$'
是一个匹配字符串' com.meraki.sm.mdm'的正则表达式。在行尾($
)找到,前面是':'。(
egrep is the same as
grep -E` - 它会激活对扩展正则表达式的支持 - 这里不是绝对必要的,但通常建议减少意外事件。)if
,则0
语句的计算结果为true,否则返回false(非零)。请注意,默认情况下,它是管道中的 last 命令,其退出代码确定管道的整体退出代码。顺便说一句,如果您只想让脚本反映是否找到字符串(即,如果您不需要在脚本中进一步操作),则以下内容就足够了:< / p>
sudo profiles -P | egrep -q ': com.meraki.sm.mdm$'
exit $? # Special variable `$?` contains the most recent command's exit code
如果您想在失败之后立即退出脚本:
sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' || exit
# Alternative, with error message:
sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' ||
{ ec=$?; echo 'Profile not installed.' >&2; exit $ec; }
相反,如果您想在成功之后立即退出:
sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' && exit