0

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
3
  • Please remember to indent your code in a more orthodox manner. Your code was unreadable at first. Highlight your code and use the {} button above the edit box to indent it 4 spaces, but the body of your function shouldn't be 30-odd spaces indented. Commented Sep 24, 2014 at 0:01
  • The variable input is not defined in validate_directory_isempty Commented Sep 24, 2014 at 0:02
  • As @linuxfan points out, $input is not defined in the function. The arguments to the function are in $1 etc; you probably want to replace $input with "$@". Also note that the function notation is not preferred; POSIX would use validate_directory_isempty() { ...code as fixed... }. Commented Sep 24, 2014 at 0:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.