【发布时间】:2018-02-22 15:43:43
【问题描述】:
我编写了一个脚本,用于启动、停止和发送 Apache 的状态,消息取决于命令的输出。
我的大部分内容都是正确的,但我的错误没有正确打印出来。换句话说,即使我没有加载 Apache,“停止”它仍然会显示成功消息。
我需要帮助,以便在必要时打印我的错误消息。
#!/bin/bash
echo -e "\e[1;30mApache Web Server Control Script\e[0m"
echo
echo "Enter the operation number to perform (1-4): "
echo " 1 - Start the httpd server"
echo " 2 - Restart the httpd server"
echo " 3 - Stop the httpd server"
echo " 4 - Check httpd server status"
echo
echo -n "===> "
read NUMBER
EXITSTATUS=$?
echo
if [ $NUMBER -eq "1" ]; then
systemctl start httpd
if [ $EXITSTATUS -eq "0" ]; then
echo -e "\e[1;32mThe return value of the command 'systemctl
start httpd' was 0.\e[0m"
echo -e "\e[1;32mThe Apache web server was successfully
started.\e[0m"
else
echo -e "\e[1;31mThe return value of the command 'systemctl
start httpd' was 5.\e[0m"
echo -e "\e[1;31mThe Apache web server was not successfully
started.\e[0m"
fi
fi
if [ $NUMBER -eq "2" ]; then
systemctl restart httpd
if [ $EXITSTATUS -eq "0" ]; then
echo -e "\e[1;32mThe return value of the command 'systemctl
restart httpd' was 0.\e[0m"
echo -e "\e[1;32mThe Apache web server was successfully
restarted.\e[0m"
else
echo -e "\e[1;31mThe return value of the command 'systemctl
restart httpd' was 5.\e[0m"
echo -e "\e[1;31mThe Apache web server was not successfully
restarted.\e[0m"
fi
fi
if [ $NUMBER -eq "3" ]; then
systemctl stop httpd
if [ $EXITSTATUS -eq "0" ]; then
echo -e "\e[1;32mThe return value of the command 'systemctl
stop httpd' was 0.\e[0m"
echo -e "\e[1;32mThe Apache web server was successfully
stopped\e[0m."
else
echo -e "\e[1;31mThe return value of the command 'systemctl
stop httpd' was 5.\e[0m"
echo -e "\e[0;31mThe Apache web server was successfully
stopped.\e[0m"
fi
fi
if [ $NUMBER -eq "4" ]; then
systemctl status httpd
if [ $EXITSTATUS -eq "0" ]; then
msg=$(systemctl status httpd)
else
echo -e "\e[1;31mThe Apache web server is not currently
running.\e[0m"
echo $(msg)
fi
fi
if [[ $NUMBER != [1-4] ]]; then
echo -e "\e[1;31mPlease select a valid choice: Exiting.\e[0m"
fi
exit 0
【问题讨论】:
-
在这里尝试猜测您的意图...您在代码中编写
EXITSTATUS=$?,然后在您应该使用$?的地方使用$EXITSTATUS的方式让我认为您的意思是EXITSTATUS作为$?的别名,因此您可以使用$EXITSTATUS作为$?的替代品。这不是它是如何工作的(正如你所发现的那样)。相反,您只是创建了一个变量 EXITSTATUS,并为其分配了$?的当前值,即 0(read命令成功)。随着代码的进行,$?的值在每个命令之后都会发生变化,但 EXITSTATUS 的值不会发生变化。这不是别名!
标签: linux bash command-line error-handling