Reputation: 175
I have an array:
src_dir=( /etc /var/www /var /var/html /home/user)
I want output like this:
/etc
/var contains /var/www /var/html
/home/user
I've tried so far:
src_dir=( /etc /var/www /var /var/html /home/user)
declare exclude
for src in ${src_dir[@]}; do
if ! [[ " $src " =~ $exclude ]]; then
exclude+=("$src")
fi
done
Upvotes: 1
Views: 47
Reputation: 8064
Try this Shellcheck-clean code:
#! /bin/bash -p
src_dir=( /etc /var/www /var /var/html /home/user)
for src in "${src_dir[@]}"; do
# Determine if $src contains other elements ($is_container), and which
# elements contain it ($containers)
is_container=0
containers=() # Elements that this element is part of
for src2 in "${src_dir[@]}"; do
if [[ $src2 == "$src" ]] ; then
# Don't count an element as being part of itself
continue
elif [[ $src == *"$src2"* ]]; then
is_container=1
break
elif [[ $src2 == *"$src"* ]] ; then
containers+=( "$src2" )
fi
done
# Skip elements that contain other elements.
# Print elements elements that don't contain other elements, and any
# elements that contain them.
if (( is_container )) ; then
continue
elif (( ${#containers[*]} > 0 )) ; then
printf '%s is contained in' "$src"
printf ' %q' "${containers[@]}"
printf '\n'
else
printf '%s\n' "$src"
fi
done
=~
) has some oddities in Bash, and is best avoided. Simple pattern matching with [[ ... == ... ]]
is sufficient here.(/home /home/user /home/user/dir)
then /home/user
will not be listed as being contained in /home/user/dir
. That may not be what you want./home/user
is considered to be contained in /home/user2
. That may not be what you want./home
and /user
will be listed as being contained in /home/user
. That may not be what you want.Upvotes: 1