Score:0

How can i check if a directory/file in my for loop is empty?

kg flag

So I have this following for loop that enters every directory and it that directory is empty it should leave it and do nothing. However if the directory isn't empty it should move its contents 1 place up and remove the remaining empty directory, but i dont know how to say: if [$i is empty] then ....

    for i in */*/
    do
      cd "$i"
    if [ -d "$i" ]
    then
        :
    else
        mv ./* ..
        cd -
        rmdir "$i"
    fi
done
ng flag
Does something bad happen if you run the `mv` command on an empty directory?
Score:1
hr flag

You can expand the directory contents into an array (portably, using the shell's positional parameter array), then test how many elements it has, ex.

#!/bin/bash

shopt -s nullglob
for d in */; do
  set -- "$d"/*
  [ $# -gt 0 ] || continue
  printf '%s: is non-empty\n' "$d"
done

Change shopt -s nullglob to shopt -s nullglob dotglob if you want to include hidden files.

If you don't like using the positional parameter array, bash supports arrays more generally ex.

#!/bin/bash

shopt -s nullglob
for d in */; do
  files=( "$d"/* )
  [ ${#files[@]} -gt 0 ] || continue
  printf '%s: is non-empty\n' "$d"
done
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.