I was trying to write a shell script that will take a directory path d as an argument and recursively print a depth indented list of all files and directories in d. However, the argument d is optional and if no argument is given, a depth indented list of all files and directories in the current directory will be printed. Here is my code:
# the method for tree
myspace=""
spaceCount=0
tree(){
cd "$1"
for i in *; do
if [ -d "$i" ]; then
echo -n "|"
for (( j=0;j<spaceCount;j++ ))
do
echo -n "$myspace"
done
echo "--$i"
spaceCount=$((spaceCount+1))
myspace=" |"
tree "$i"
else
echo -n "|"
for (( j=0;j<spaceCount;j++ ))
do
echo -n "$myspace"
done
echo "--$i"
fi
done
cd ../
spaceCount=$((spaceCount-1))
}
if [ "$1" != "" ]; then
file="$1"
fi
echo ".$file"
tree "$file"
But when a folder is empty, it's printing a star like this:
How can I solve the problem?
shopt -s nullglob
? – sphoenix Oct 05 '17 at 17:52[ -e "$i" ] || continue
at the start or yourfor
loop to filter out the*
by checking for file existence (would affect the behaviour for directories you have read but not search permissions to though). Could you kindly elaborate on "would affect the behaviour for directories you have read but not search permissions to though", please? – sphoenix Oct 05 '17 at 17:56