Search code examples
shellunix-text-processing

How to create dynamic IF condition


I have been writing a script which will run in while loop infinite times

If all condition are met then only the script will break and execute another command

My code :

while true
do 
   
   # Note : below field will execute some command and generate value   
   field1=`some command which gives status`
   field2=`some command which gives status`
   field3=`some command which gives status`
   field4=`some command which gives status`

   if [ "$field1" == "A" ] &&  [ "$field2" == "A" ] && [ "$field3" == "A" ] && [ "$field4" == "A" ] 
   then
         break
   else
         echo "Conditions are not met !!!" 
   fi 
done

echo "Another command execution started ... "

The issue here is the number of fields might vary

Need to make my script generic and incase I have 10 fields also it should frame a

if condition dynamically and start executing until all fields becomes equal to A and break for executing another command


Solution

  • Assuming all "success" return status is A, is a single character length.

    We can aggregate all return status code into a long string. Than try to search for a non A value.

    local ret_val=""
    while true; do 
       
       # Note : below field will execute some command and generate value   
       ret_val="${ret_val}$(some command1 which gives status)"
       ret_val="${ret_val}$(some command2 which gives status)"
       ret_val="${ret_val}$(some command3 which gives status)"
       ret_val="${ret_val}$(some command4 which gives status)"
    
       if [[ ${ret_val} =~ "[^A]*" ]]; then
         echo "Conditions are not met !!!" 
       else
         break
       fi 
    done
    
    echo "Another command execution started ... "
    
    

    If all "success" return status is a multi-digit number.

    You can convert the numeric return status to a single character, see in this answer.