1

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
0

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx, U made my day. Now it works and I can implement it in the larger script.

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.