Script working successfully only when executed twice

Guys,

i am facing a very strange issue, my code below does an ftp to server A and gets a file to Server B, once the file is in B an if condition is present to check if the pattern of the filename is ABC* then it has to be encrypted using OPENSSL as ABC.enc else if it of pattern 123* has to be encrypted in a different way.

My issue is that the script has to be executed twice to get the expected result. The First execution itself does not perform the encryption. This occurs for files of large and small size.

./getfile_encrypt.ksh;
 
ABCCount=`ls -lrt ABC* | awk '{print ($9)}' | wc -l`;
 
echo "FTP IS DONE"
 
if [[ ${ABCCount} -gt 0 ]] then
 
     echo "BEFORE OPENSSL"
     OPENSSL......
     echo "AFTER OPENSSL"
fi

the getfile_encrypt.ksh just performs an FTP and gets the file.

when i execute the script, i get the following

 
FIRST TIME
 $ ./encrypt_ABC.ksh
 ls: 0653-341 The file ABC* does not exist.
 THE FTP IS DONE
 
SECOND TIME
 $ ./encrypt_ABC.ksh
  THE FTP IS DONE
 JUST BEFORE OPENSSL
 JUST AFTER OPENSSL

Please let me know why the script is exiting half way the first time and the second time it is executed, it runs successfully eventhough i do not make any change. eventhough it says ABC* does not exist the first time, it is present in the local path of the server B.

It isn't present yet otherwise it wouldn't say ABC* doesn't exist.

Change the "ls -lrt" to "ls -1rt" and get rid of the awk command.
You should also redirect stderr from the ls to /dev/null.

you must start the script when FTP proccessing completely succesfully finished