BhishanPoudel
BhishanPoudel

Reputation: 17154

Bash function to continue run if all files have size less than something

I have little exposure to Bash scripting. I am trying to implement a bash function that runs some commands only if previous commands are successful. Particularly, here, I want to run the function if all the file sizes are less than a certain size.

MWE

function myfunc() {
    files=`find . -type f -size +1M -print0 | xargs -0 du -h | sort -rh`
    echo "Files larger than 1MB ${files}"

    if len(files) > 0 then
        echo "At least one file has larger size, stopping the function"
    else
        echo "All files are less than size X, run other commands"
        echo "success"
    fi
}

How to make the function work?

Upvotes: 0

Views: 95

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295443

If you want to count the number of items in a variable, that variable should be an array.

In this case, it makes more sense to store an array with the list of raw files, and run it through du and sort only for output purposes:

#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-2].*) echo "ERROR: bash 3.x needed" >&2; exit 1;; esac

myfunc() {
    # bash 3.0-compatible; readarray requires bash 4
    local file; local -a files=( )
    while IFS= read -r -d '' file; do
      files+=( "$file" )
    done < <(find . -type f -size +1M -print0)

    echo "${#files[@]} found larger than 1MB" >&2

    if (( ${#files[@]} > 0 )); then
        # actually print a listing of our larger files
        printf '%s\0' "${files[@]}" | xargs -0 du -h | sort -rh >&2
        echo "At least one file has larger size, stopping the function" >&2
    else
        echo "All files are less than size X, run other commands" >&2
        echo "success"
    fi
}

myfunc "$@"  # actually start our function

Note that output written for user consumption, rather than for other software to read, should be on stderr; hence the >&2s.

Upvotes: 1

Related Questions