Reputation: 45
I don't know what is wrong with my function; it is not returning value properly.
function validate_directory_isempty {
retval=""
NumOfFiles=`ls -l $input | egrep -c "^-"`
if [ "$NumOfFiles" == "0" ];then
retval=true
else
retval=false
fi
echo $retval
}
retval=$(validate_directory_isempty /opt/InstallationManager)
echo "retval : " $retval
if [ "$retval" == "true" ]; then
echo ""
echo "Installing Installation Manager"
# Install_IM
else
echo ""
echo "DIRECTORY is not empty. Please make sure install location $DIRECTORY is empty before installing PRODUCT"
fi
Upvotes: 0
Views: 292
Reputation: 45
i just replaced my script as below and it worked
removed the below commands retval=$(validate_directory_isempty /opt/InstallationManager) echo "retval : " $retval
added input=/opt/InstallationManager validate_directory_isempty
and it worked.
Thanks again for your valuable inputs
Upvotes: 0
Reputation: 247210
The idiomatic way to have a function return true or false is to use the return
keyword. A return value of 0 means success, a non-zero value means failure. Also note that a function will return with a status of the last command executed if return
is not present.
I would write your function like this
is_dir_empty() {
shopt -s nullglob
local -a files=( "$1"/* )
(( ${#files[@]} == 0 ))
}
directory=/opt/InstallManager
if is_dir_empty "$directory"; then
echo "$directory" is empty
fi
The first line sets a shell option that pattern matching no files expands to null instead of the pattern itself as a string.
The second line fills an array with the filenames in the given directory.
The last line tests the number of elements in the array. If zero entries, return success else return failure.
Upvotes: 1