title: Looping on variables with a condition in bash (Stopping services in a specific order)
body: <p>I'm creating a script in bash to perform the below use cases,</p>
  <ul>
  <li>Finding specific services based on specific words on their names</li>
  <li>Stopping these services <strong>in a specific order like: service_1, service_2 and so on</strong></li>
  <li>Checking if these services are stopped and <strong>if there is a one that is still up &amp; running, It will print out it's name</strong></li>
  </ul>
  <p>This is my progress,
  Firstly, I've found the services based on some words that only exists with their names as below,</p>
  <pre><code>service_1=$(ls /etc/systemd/system | grep -e text1 | awk -F ' ' '{print $1}')
  service_2=$(ls /etc/systemd/system | grep -e text2 | awk -F ' ' '{print $1}')
  service_3=$(ls /etc/systemd/system | grep -e text3 | awk -F ' ' '{print $1}')
  </code></pre>
  <p>Then, I've stopped them in the order I want as below:</p>
  <pre><code>if [ ! -z &quot;$service_1&quot; ] //if service exists
  then
        systemctl stop $service_1
  else
        :
  fi
  
  if [ ! -z &quot;$service_2&quot; ] //if service exists
  then
        systemctl stop $service_2
  else
        :
  fi
  
  if [ ! -z &quot;$service_3&quot; ] //if service exists
  then
        systemctl stop $service_3
  else
        :
  fi
  </code></pre>
  <p>Here comes the problem. As you know, when stopping a service, it may take some time to be fully stopped so as per the conditions above it will move forward in stopping the second service without full stopping the previous one. What I want is stopping the services in order so before stopping the second service the first one should be fully stopped and so on. How to make that ? I think this can be made by loops but I am missing the way.
  Regarding the third use case, I've defined the below variables that holds the word &quot;inactive&quot; after filtering the status output of the services as an indicator that the services are stopped:</p>
  <pre><code>service_1_status=$(systemctl status $service_1 | grep -e &quot;inactive&quot;)
  service_2_status=$(systemctl status $service_2 | grep -e &quot;inactive&quot;)
  service_3_status=$(systemctl status $service_3 | grep -e &quot;inactive&quot;)
  </code></pre>
  <p>Then, I've tried to loop on them to find out if there is a service that is still active to print it's name as below:</p>
  <pre><code>arr=($service_1_status $service_2_status $service_3_status $service_q_inf_status)
  for i in &quot;${arr[@]}&quot;
  do
        if &quot;${arr[$i}&quot; != &quot;inactive&quot;
        then
              echo $i
        else
              echo &quot;All Services are now Stopped&quot;
        fi
  done
  </code></pre>
  <p>I don't know if this syntax if fully operational or not as it doesn't work but this is the logic I want to do. What is the proper way to do this ?</p>