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"
fi
The 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?
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"
fi
If 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"/*
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments