Take the 2-minute tour ×

My task is to list a user's folder in /Users on a mac. I have to allow for dupe folders (large enterprise of 650 mac clients) or where a desktop analyst has backed up a folder and appended something. My $fourFour variable picks that up. However, I must flag that for logging.

This is where I have got below. The variable $fourFour may return one or more folders and I need to get the if statement to echo this accordingly.

folders=$(ls -d */ | grep $fourFour | awk '{print $(NF)}' | sed 's/\///')
echo folders is $folders
if [[ "$folders" == "" ]]; then
    echo no items
    echo one or more items
share|improve this question
It would be better if you can tell us what you are trying to do. YOu can definitely avoid 4 piped commands on 1st line. –  anubhava Apr 21 '11 at 15:42
add comment

2 Answers

up vote 2 down vote accepted
  1. Do not parse the output of ls unless you absolutely have to. Your code above has major issues with whitespace in folder names.

  2. Bash arrays can be your friend:

    shopt -s nullglob
    # Remove the trailing slashes
    if [[ "${#folders[@]}" -gt 0 ]]; then
        echo "Folders:" "${folders[@]}"
        echo "No folders"
share|improve this answer
This works for me if I modify the greater than to 1 and echo "only one folder" or otherwise echo "more folders" - thanks. –  Chris Hopkins Apr 21 '11 at 16:03
add comment

you don't have to call so many tools to find your folders. Just use the shell (bash)

shopt -s nullglob 
for dir in *$fourFour*/  # putting a slash "/" ensures you get directory entries
   echo "Do something with $dir"
   # if you want to check if its empty folder
   v=$(echo "$dir"/*)
   case "${#v}" in
     0) echo "No files in $dir";;
     *) echo "Files in $dir";;

if you just want to check whether there are any folders that matched your pattern

v=$(echo "$four"/)
case "${#v}" in
     0) echo "0 item";;
     *) echo "1 or more item";;
share|improve this answer
I don't think that's what he wants : he wants to echo if there are "no items" or "one or more items". –  Matthieu Napoli Apr 21 '11 at 15:39
it is not clear whether he wants to check if there are folders matching his grep pattern, or if he wants to check whether the folders matched contains 0 files (or not). –  bash-o-logist Apr 21 '11 at 15:41
add comment

Your Answer


