skip to Main Content

I want to check the validity of my nginx configuration using nginx -t using it as a condition for a bash script.

if [[ $(nginx -t) = *"successful"* ]]; then 
echo "success"; 
else 
echo "failure"; 
fi

While the output of nginx -tcontains successful, bash prints failure regardless. What am I doing wrong?

EDIT: I don’t want to check by exit code but by string output.

Solution:

if [[ $(nginx -t 2>&1) = *"successful"* ]]; then 
echo "success"; 
else 
echo "failure"; 
fi
```

2

Answers


  1. Here is my (working) script to do the same:

    nginx -t >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "success"
    else
        echo "failure"
    fi
    
    Login or Signup to reply.
  2. What am I doing wrong?

    You are expecting the message to printed on stdout. It is printed on stderr. Redirect stderr to stdout to capture the message.

    If you want to capture stderr and stdout of a command and also check it’s exit status, do:

    if out=$(nginx -t 2>&1); do
        echo "success"
    else
        echo "failure, because: $out"
    fi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search