Leo
Leo

Reputation: 178

bash spaces in dir names using find cause linebreaks in ls

I have not been able to handle spaces in filenames

The script: With find I select all directories, they are fed in ls for counting number of files in the directory

The bash code:

#!/bin/bash

for adir2 in $(find . -type d);
do
        echo "[$adir2]"
        DIRCOUNT=$(ls -1A $adir2 |wc -l)
        if [ $DIRCOUNT -eq 0 ]; then
          echo $adir2 "is empty"
        fi
done

Test set-up:

mkdir testdir
cd testdir
mkdir 01\ dir

Running the script here

The result:

[.]
[./dir]
./dir is empty
[./01]
ls: cannot access './01': No such file or directory
./01 is empty
[dir]
dir is empty

I'm using Ubuntu 20

Remark: The following doesn't work:

find /path/to/dir -empty -type d

All dirs are shown. Apparently the empty property is not there. The location is an external USB-drive with ext4 partition.

Upvotes: 0

Views: 92

Answers (1)

Philippe
Philippe

Reputation: 26537

This should do what you wanted:

#!/usr/bin/env bash

while read -d '' adir2
do
        echo "[$adir2]"
        dircount=$(ls -1A "$adir2" | wc -l)
        if [ "$dircount" -eq 0 ]; then
          echo "[$adir2] is empty"
        fi
done < <(find . -type d -print0)

Try to avoid using all-uppercase variables.

Upvotes: 4

Related Questions