Home > database >  bash - not finding value present in an array
bash - not finding value present in an array

Time:02-15

I have an array of empty subdirectories and when I loop through all of the subdirectories I want to do something different depending on if it is in the array of empty subdirectories or not.

My issue is that I don't think my script is picking up on if a value is in the empty directories array. When I loop through the arrays and echo their values I can see that some values are in both arrays so I don't know why they aren't being picked up.

Code:

readarray empty_dirs < <(find /local/documents/guests/* -maxdepth 0 -empty)
for f in "${empty_dirs[@]}"
do
    echo $f
    echo "------------------------"
done


guest_path=/local/documents/guests/guest*
guest_arr=( $guest_path )
for dir in "${guest_arr[@]}"
do
    echo "$dir"
    if [[ " ${empty_dirs[@]} " =~ " ${dir} " ]];then
        echo "--- $dir found ---"
    fi
done

Output:

/local/documents/guests/guest10
------------------------
/local/documents/guests/guest12
------------------------
/local/documents/guests/guest15
------------------------
/local/documents/guests/guest18
------------------------
/local/documents/guests/guest20
------------------------

/local/documents/guests/guest1
/local/documents/guests/guest10
/local/documents/guests/guest11
/local/documents/guests/guest12
/local/documents/guests/guest13
/local/documents/guests/guest14
/local/documents/guests/guest15
/local/documents/guests/guest16
/local/documents/guests/guest17
/local/documents/guests/guest18
/local/documents/guests/guest19
/local/documents/guests/guest2
/local/documents/guests/guest20
/local/documents/guests/guest21
/local/documents/guests/guest22
/local/documents/guests/guest23
/local/documents/guests/guest24
/local/documents/guests/guest25
/local/documents/guests/guest3
/local/documents/guests/guest4
/local/documents/guests/guest5
/local/documents/guests/guest6
/local/documents/guests/guest7
/local/documents/guests/guest8
/local/documents/guests/guest9

CodePudding user response:

The problem is ${empty_dirs[@]} contains the names including trailing newlines.

You can stop storing them using the -t option of readarray, or remove them before running the final loop:

empty_dirs=${empty_dirs[@]%$'\n'}
  •  Tags:  
  • bash
  • Related