Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash determine if variable is empty and if so exit.

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 
like image 975
user2653557 Avatar asked Nov 07 '13 14:11

user2653557


People also ask

What is if [- Z in bash?

Use the -z Flag in Bash The -z flag is a parameter that checks if the length of a variable is zero and returns true if it is zero. In the example below, the -z flag is used with the test command, and it is tested whether the given string is empty. Bash.

How do you know if a variable is empty?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


1 Answers

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

like image 166
Pipo Avatar answered Oct 16 '22 07:10

Pipo