bashwhile-loopuntil-loop

BASH - getting invalid response when using until or while loop


I was able to create the if-elif-then-else code block on a separate script and validated working fine. However when I added the UNTIL or WHILE logic I'm getting the invalid response. I'm NOT expecting to get this response = "invalid operation" if I manually created the VALIDATE.txt file with either "proceed" or "rollback" inside the file. Please check my code below

WHILE SCRIPT

#!/bin/bash
FILE=/Users/lagot/Documents/BASH-TEST/VALIDATE.txt
ACTION=`cat /Users/lagot/Documents/BASH-TEST/VALIDATE.txt >>/dev/null 2>&1`
while [ ! -f "$FILE" ]
do
  echo "not exist"
  sleep 60
done

  if [ "${ACTION}" = "proceed" ];
    then
      echo "performing proceed"
      rm -rf $FILE
  elif [ "${ACTION}" = "rollback" ];
    then
      echo "performing rollback"
      rm -rf $FILE
  else
      echo "invalid operation"
      rm -rf $FILE
  fi

UNTIL SCRIPT

#!/bin/bash
FILE=/Users/lagot/Documents/BASH-TEST/VALIDATE.txt
ACTION=`cat /Users/lagot/Documents/BASH-TEST/VALIDATE.txt >>/dev/null 2>&1`
until [ -f "$FILE" ]
do
   echo "not exist"
   sleep 60
done
if [ "${ACTION}" = "proceed" ];
  then
    echo "performing proceed"
    rm -rf $FILE
elif [ "${ACTION}" = "rollback" ];
  then
    echo "performing rollback"
    rm -rf $FILE
else
    echo "invalid operation"
    rm -rf $FILE
fi

I created the VALIDATE.txt on a separate window and checked myself

lagot-pc:BASH-TEST lagot$ echo proceed >> VALIDATE.txt
lagot-pc:BASH-TEST lagot$ pwd
/Users/lagot/Documents/BASH-TEST
lagot-pc:BASH-TEST lagot$ cat /Users/lagot/Documents/BASH-TEST/VALIDATE.txt
proceed

I'm getting the invalid response "invalid operation" instead of "performing proceed" same also if I try to create the VALIDATE.txt and echo the "rollback" inside of the file

lagot-pc:BASH-TEST lagot$ ./while-script.sh
not exist
not exist
not exist
not exist
not exist
invalid operation

Solution

  • This is now fixed, I also added the new format of UNTIL and WHILE scripts below

    FIX IN WHILE SCRIPT

    #!/bin/bash
    FILE=/Users/lagot/Documents/BASH-TEST/VALIDATE.txt
    
    while [ ! -f "$FILE" ]
    do
      echo "not exist"
      sleep 60
    done
    
      if [ `cat "$FILE"` = "proceed" ];
        then
          echo "performing proceed"
          rm -rf $FILE
      elif [ `cat "$FILE"` = "rollback" ];
        then
          echo "performing rollback"
          rm -rf $FILE
      else
          echo "invalid operation"
          rm -rf $FILE
      fi
    

    FIX IN UNTIL SCRIPT

    #!/bin/bash
    FILE=/Users/lagot/Documents/BASH-TEST/VALIDATE.txt
    
    until [ -f "$FILE" ]
    do
       echo "not exist"
       sleep 60
    done
    if [ `cat $FILE` = "proceed" ];
      then
        echo "performing proceed"
        rm -rf $FILE
    elif [ `cat $FILE` = "rollback" ];
      then
        echo "performing rollback"
        rm -rf $FILE
    else
        echo "invalid operation"
        rm -rf $FILE
    fi