How to check if find command didn't find anything?

后端 未结 6 400
抹茶落季
抹茶落季 2021-01-01 14:11

I know that is possible to use for loop with find command like that

for i in `find $something`; do (...) done

but I want to use find comma

相关标签:
6条回答
  • 2021-01-01 14:36

    Exit 0 is easy with find, exit >0 is harder because that usually only happens with an error. However we can make it happen:

    if find -type f -exec false {} +
    then
      echo 'nothing found'
    else
      echo 'something found'
    fi
    
    0 讨论(0)
  • 2021-01-01 14:38

    I wanted to do this in a single line if possible, but couldn't see a way to get find to change its exit code without causing an error.

    However, with your specific requirement, the following should work:

    find /directory/whatever -name '*.tar.gz' -mtime +$DAYS | grep 'tar.gz' || echo "You don't have files older than $DAYS days"
    

    This works by passing the output of find into a grep for the same thing, returns a failure exit code if it doesn't find anything, or will success and echo the found lines if it does.

    Everything after || will only execute if the preceding command fails.

    0 讨论(0)
  • 2021-01-01 14:39

    You want to use find command inside an if condition , you can try this one liner :

     [[ ! -z `find 'YOUR_DIR/' -name 'something'` ]] && echo "found" || echo "not found"
    

    example of use :

     [prompt] $ mkdir -p Dir/dir1 Dir/dir2/ Dir/dir3                 
     [prompt] $ ls Dir/
     dir1  dir2  dir3
     [prompt] $ [[ ! -z `find 'Dir/' -name 'something'` ]] && echo "found" || echo "not found"
     not found
     [prompt] $ touch Dir/dir3/something
     [prompt] $ [[ ! -z `find 'Dir/' -name 'something'` ]] && echo "found" || echo "not found"
     found
    
    0 讨论(0)
  • 2021-01-01 14:40

    Iterating over the output of find might be dangerous if your filenames contain spaces. If you're sure they don't, you can store the result of find to an array, and check its size to see there were any hits:

    results=( $(find -name "$something") )
    if (( ${#results[@]} )) ; then
        echo Found
    else
        echo Not found
    fi
    for file in "${results[@]}" ; do
       # ...
    done
    
    0 讨论(0)
  • 2021-01-01 14:44

    Count the number of lines output and store it in a variable, then test it:

    lines=$(find ... | wc -l)
    if [ $lines -eq 0 ]; then
    ...
    fi
    
    0 讨论(0)
  • 2021-01-01 14:48

    This worked for me

    if test $(find . -name "pattern" | wc -c) -eq 0
    then
        echo "missing file with name pattern"
    fi
    
    0 讨论(0)
提交回复
热议问题