bash determine if variable is empty and if so exit.

user2653557 picture user2653557 · Nov 7, 2013 · Viewed 31.1k times · Source

I am trying to perform this: i have a test file which md5sum of files located on sftp. variables should contain an md5sum (string), if the variable is empty it means there is no file on the sftp server. i am trying this code but it does not work..

    if [ -z $I_IDOCMD5 ] || [ -z $I_LEGALMD5 ] || [ -z $I_ZIPMD5 ]
then
        echo "ERROR: At least one file not present of checksum missing no files will be deleted" >>$IN_LOG
        ERRORS=$ERRORS+2
else
 if [[ $I_IDOCMD5 == $($DIGEST -a md5 $SAPFOLDER/inward/idoc/$I_IDOC) ]]
   then
        echo "rm IDOC/$I_IDOC" >/SAP/commands_sftp.in
   else
        echo "problem with checksum"
        ERRORS=$ERRORS+2
 fi

 if [[ $I_LEGALMD5 == $($DIGEST -a md5 $SAPFOLDER/inward/legal/$I_LEGAL) ]]
   then
        echo "rm LEGAL/$I_LEGAL" >>/SAP/commands_sftp.in
   else
        echo "problem with checksum"
        ERRORS=$ERRORS+2
 fi

 if [[ $I_ZIPMD5 == $($DIGEST -a md5 $SAPFOLDER/inward/zip/$I_ZIP) ]]
   then
        echo "rm ZIP/$I_ZIP" >>/SAP/commands_sftp.in
   else
        echo "problem with checksum"
        ERRORS=$ERRORS+2
fi

Answer

Pipo picture Pipo · Mar 27, 2015

The answer I prefer is following

[[ -z "$1" ]] && { echo "Parameter 1 is empty" ; exit 1; }

Note, don't forget the ; into the {} after each instruction