b0red
b0red

Reputation: 47

Bash function not returning the value as expected

This is a small portion of a larger script, but it doesn't show the right result. I want it to check for a folder, if that folder exists then check for number of files in it. If empty then exit (continue with larger script). Or maybe it should be a large function? The script:

#!/bin/bash
BU_DIR=~/Backups

function Func_CountFiles() {
    FILES=$(find ${BU_DIR} -type f | wc -l )
    # echo $BU_FILES
}

###     Get files from Backupfolder
#
if [ ! -d "${BU_DIR}" ]; then
    BU_Status="Directory, ($BU_DIR), not found!"
    else
        Files=$(Func_CountFiles)
        if [ $Files -le "0" ]; then
            FU_Status="Current dir, ($BU_DIR), is empty."
        else
            # Files=$(Func_CountFiles)
        BU_Status="Current dir, ($BU_DIR), contains $Files."
        fi
fi
exit 0

Upvotes: 1

Views: 210

Answers (1)

Inian
Inian

Reputation: 85590

The idea is right, but you are not returning anything to the calling function. You need the return the value by printing the variable value FILES. Only then the variable Files in the calling function is updated with the count you are determining in the Func_CountFiles(). Do

function Func_CountFiles() {
    fileCount=$(find ${BU_DIR} -type f | wc -l )
    printf "%d" "$fileCount"
}

and capture the value of called function as

declare -i file_count_from_function 
file_count_from_function=$(Func_CountFiles)
printf "%d\n" "$file_count_from_function"

and since you are using bash use its own arithmetic operator ((..)) for numeric evaluations. You can use the variables for arithmetic evaluations just as you do in C programming.

if (( file_count_from_function <= 0 )); then

Upvotes: 2

Related Questions