我搜索了 SO 但找不到任何与此特定问题相关的帖子。我想知道如何调用存储在另一个 shell 脚本变量中的 shell 脚本。 在下面的脚本中,我试图读取服务名称和相应的 shellscript,检查服务是否正在运行,如果没有,使用与该服务名称关联的 shell 脚本启动服务。尝试了在各种论坛(如“eval”等)中共享的多个选项,但没有成功。请帮助提供您对此的建议。
checker.sh
#!/bin/sh
while read service
do
servicename=`echo $service | cut -d: -f1`
servicestartcommand=`echo $service | rev | cut -d: -f1 | rev`
if (( $(ps -ef | grep -v grep | grep $servicename | wc -l) > 0 ))
then
echo "$servicename Running"
else
echo "!!$servicename!! Not Running, calling $servicestartcommand"
eval "$servicestartcommand"
fi
done < names.txt
姓名.txt
WebSphere:\opt\software\WebSphere\startServer.sh
WebLogic:\opt\software\WebLogic\startWeblogic.sh
最佳答案
您的脚本可以重构为:
#!/bin/bash
while IFS=: read -r servicename servicestartcommand; do
if ps cax | grep -q "$servicename"; then
echo "$servicename Running"
else
echo "!!$servicename!! Not Running, calling $servicestartcommand"
$servicestartcommand
fi
done < names.txt
- 无需在
grep
的输出后使用wc -l
,因为您可以使用grep -q
- 无需使用读取整行然后使用
cut
、rev
等。您可以使用IFS=:
并将该行读入 2 个单独的变量 - 最后不需要使用
eval
关于linux - 调用存储在另一个 shell 脚本变量中的 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35170733/