Bash退出状态在脚本中不起作用

时间:2018-02-22 15:43:44

标签: linux bash command-line error-handling

我编写了一个启动,停止和发送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

2 个答案:

答案 0 :(得分:2)

变量EXITSTATUS不包含systemctl调用的退出代码,而是包含read命令的退出代码。您可以将其重写为

systemctl start httpd
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
[...]

或更简单地作为

systemctl start httpd
if [ $? -eq 0 ]; then
[...]

只有当您想要在其他地方使用它(例如作为您自己脚本的退出代码)时才需要将$?的值存储在变量中,或者必须在分支之前进行其他调用。值。

答案 1 :(得分:1)

您在运行命令后未设置变量$EXITSTATUS,因此它保持其原始值(read NUMBER的退出状态)。

由于您只关心命令是否成功,因此最好避免完全使用它并将条件更改为例如:

if systemctl restart httpd; then
  # it was successful ($? would be 0)
fi