Monday, May 20, 2024
13
rated 0 times [  13] [ 0]  / answers: 1 / hits: 8089  / 2 Years ago, tue, may 10, 2022, 8:12:07

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?


More From » command-line

 Answers
7

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"/*

[#2758] Wednesday, May 11, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ingsta

Total Points: 391
Total Questions: 103
Total Answers: 124

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;