Thall
Thall

Reputation: 99

If bool statement with function

I'm attempting to write a function that has an if statement that uses the original function's variable and another function. I want to move documents only if the directory passed in actually contains documents:

documentCheck() {
   if [ "$(ls -A ./$1)" ]; then
      return 0   # found documents
   else
      return 1   # did not find documents
   fi
}

moveFiles() {
   if [ documentCheck $1 ]; then
      mv ./$1/* ~/Desktop
   else
      echo "$1 does not contain documents."
   fi
}

moveFiles Inbox
moveFiles Archive

Ideally, I'm trying to have my moveFile function only move files if it's able to verify that the folder contains documents because I'll end up having a few separate functions that all need to verify if documents exist in folders.

Thanks in advance for any help.

Upvotes: 2

Views: 44

Answers (2)

llogiq
llogiq

Reputation: 14511

You can do the following:

documentCheck() {
   if [ "$(ls -A ./$1)" ]; then
      true   # found documents
   else
      false   # did not find documents
   fi
}

moveFiles() {
   documentCheck $1 && mv ./$1/* ~/Desktop || echo "$1 does not contain  documents."
}

moveFiles Inbox
moveFiles Archive

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84561

Use -z to test for empty and don't quote the entirety of the inside of the conditional test. E.g.:

if [ -z "$(ls -A "$1")" ]; then
    echo "$1 -- has no files"
else
    echo "$1 -- has files"

Upvotes: 2

Related Questions