bash检查服务是否安装的最佳方法是什么?它应该适用于Red Hat(CentOS)和Ubuntu?
思维:
service="mysqld" if [ -f "/etc/init.d/$service" ]; then # mysqld service exists fi
也可以使用该service
命令并检查返回码.
service mysqld status if [ $? = 0 ]; then # mysqld service exists fi
什么是最好的解决方案?
Rustam Mamat因此得到了赞誉:
如果列出所有服务,您可以查看结果以查看其中的内容.例如:
# Restart apache2 service, if it exists. if service --status-all | grep -Fq 'apache2'; then sudo service apache2 restart fi
要获得一项服务的状态而不“ ping”所有其他服务,可以使用以下命令:
systemctl list-units --full -all | grep -Fq "$SERVICENAME.service"
顺便说一下,这就是bash(自动)完成中使用的东西(请参见文件/ usr / share / bash-completion / bash_completion,查找_services):
COMPREPLY+=( $( systemctl list-units --full --all 2>/dev/null | \ awk '$1 ~ /\.service$/ { sub("\\.service$", "", $1); print $1 }' ) )
或更详细的解决方案:
service_exists() { local n=$1 if [[ $(systemctl list-units --all -t service --full --no-legend "$n.service" | cut -f1 -d' ') == $n.service ]]; then return 0 else return 1 fi } if service_exists systemd-networkd; then ... fi
希望对您有所帮助。