I need to check if a folder is empty or not and according to the output I need to run some other commands. I'm working on Ubuntu 18.04.5 LTS.
My bash script:
if [ "$(ls -A /mnt/mamdrive/"As Metadata"/)" ] || ["$(ls -A /mnt/mamdrive/"As Video"/)" ]; then echo "copy file"
else echo "dont copy"
fiThe condition works sometimes, but sometimes it doesn't and it's hard to reproduce it. Is there any other way to check if the directory is empty and do some action accordingly?
25 Answers
I'd suggest something that doesn't rely on the string output of ls - for example, testing if there are any results of a glob expansion:
#!/bin/bash
shopt -s nullglob # don't return literal glob if matching fails
shopt -s dotglob # make * match "almost all" like ls -A
set -- /mnt/mamdrive/"As Metadata"/*
if (( $# > 0 )); then echo "not empty"
else echo "empty"
fiIf you want to test whether two directories are both empty, you can simply glob both of them:
set -- /mnt/mamdrive/"As Metadata"/* /mnt/mamdrive/"As Video"/* 3 The easiest way is to use ls -A in an if statement like this:
path=$(ls -A '/whatever/sub directory/more spaces')
if [[ ! -z "$path" ]]; then echo "Directory is NOT empty!"
else echo "Directory is empty!"
fi 4 find in conjunction with ifne can work as a copy-on-empty:
$ find test/ -maxdepth 0 -empty | ifne cp -t test/ aUsing it in an if statement can look something like this:
#!/bin/bash
if find test/ -maxdepth 0 ! -empty | ifne false; then echo Directory is empty
else echo Directory is not empty
fi As ls parsing is very well known to be error-prone because it was not intended to be parsable to begin with, other solutions should be preferred. In addition to @steeldriver's answer, this could also be done using find:
if [[ "$(find '/mnt/mamdrive/As Metadata' '/mnt/mamdrive/As Video' -maxdepth 1 -mindepth 1 2>/dev/null)" ]]
then echo “copy file”
else echo "don't copy"
fimaxdepth and mindepth options are used here to only print and scan direct children of specified directories. Redirect ensures that error messages will not be printed if some arguments do not exist.
Adding multiple dirs will work as OR, so "copy file" will be printed if at least one of tested dirs is non-empty. Using find also allows for finer tuning using its arguments, like file names, file types and so much more.
I have been using the following to check if folder is empty or not and so far it has always worked
if [ $(ls -al folder_name | wc -l) -gt 3 ];then echo "not empty";else echo "empty";fi