Most often, when you search something extremly simple and obvious, you have a hard time finding it. The simpler and the more obvious, the harder. This time I wanted to send a listing of a directory structure per email, no complex content, no HTML no Doc (how again do you export directory-trees directly into a graphic or document?).
Here is the result (public domain):
#!/bin/bash
target=.
prefix=
last=
if test $# -gt 0; then
target="$1"
fi
if test $# -gt 1; then
prefix="$2"
fi
############################################################
# to make files-first-dirs-last:
# - scan files first seperatly
# - scan directories after seperatly
############################################################
# determine which is the last entry
# can either be a file or a directory
for sub in "$target"/*; do
if test -f "$sub"; then
num=$(ls -1 "$sub" | wc -l)
if [ $num -gt 0 ]; then
last=”$sub”
fi
fi
done
for sub in “$target”/*; do
if test -d “$sub”; then
num=$(ls -1 “$sub” | wc -l)
if [ $num -gt 0 ]; then
last=”$sub”
fi
fi
done
############################################################
# print the files available in the given directory
# then determine if there are parent-directories
# that also contain files, which we enter only if yes
for sub in “$target”/*; do
if test -f “$sub”; then
if [ "$last" != "$sub" ]; then
echo “$prefix” \+- ${sub#$target\/}
fi
if [ "$last" = "$sub" ]; then
echo “$prefix” \`- ${sub#$target\/}
fi
fi
done
for sub in “$target”/*; do
if test -d “$sub”; then
num=$(ls -1 “$sub” | wc -l)
if [ $num -gt 0 ]; then
echo “$prefix” \|
if [ "$last" != "$sub" ]; then
echo “$prefix” \+- ${sub#$target\/}
echo “$prefix” \|\ \ \|
treef “$sub” “$prefix | ”
fi
if [ "$last" = "$sub" ]; then
echo “$prefix” \`- ${sub#$target\/}
echo “$prefix” \ \ \ \|
treef “$sub” “$prefix ”
fi
fi
fi
done
If you got faster variatoins of this quick hack fitting my needs, I’m going to update the code with your suggestions. Here BTW is an example of the output:
$ treef Windows\ NT
+- htrn_jis.dll
+- hypertrm.exe
|
+- Accessories
| |
| +- mswrd6.wpc
| +- mswrd8.wpc
| +- wordpad.exe
| `- write.wpc
|
`- Pinball
|
`- New Textdokument.txt