morristech
6/29/2019 - 12:54 AM

Show file listing as tree

Show file listing as tree

Show file listing as tree structure

This is a very small and simple bash script to show a file listing as a tree structure:

$ tree /etc/apache2
+- extra
|  +- httpd-autoindex.conf
|  +- httpd-dav.conf
|  +- httpd-default.conf
|  +- httpd-info.conf
|  +- httpd-languages.conf
|  +- httpd-manual.conf
|  +- httpd-mpm.conf
|  +- httpd-multilang-errordoc.conf
|  +- httpd-ssl.conf
|  +- httpd-userdir.conf
|  +- httpd-vhosts.conf
+- httpd.conf
+- magic
+- mime.types
+- original
|  +- extra
|  |  +- httpd-autoindex.conf
|  |  +- httpd-dav.conf
|  |  +- httpd-default.conf
|  |  +- httpd-info.conf
|  |  +- httpd-languages.conf
|  |  +- httpd-manual.conf
|  |  +- httpd-mpm.conf
|  |  +- httpd-multilang-errordoc.conf
|  |  +- httpd-ssl.conf
|  |  +- httpd-userdir.conf
|  |  +- httpd-vhosts.conf
|  +- httpd.conf
+- other
|  +- php5.conf
+- users

Sometimes a tree just gives better overview than a simple find . -type f.

#!/usr/bin/env bash

# Show files in a tree structure
#
# @param 1 - root directory
# @param 2 - level
tree() {
	local F N=0 L='|' D=${1:-.}

	for F in "$D"/*
	do
		[ -r "$F" ] && (( ++N ))
	done

	for F in "$D"/*
	do
		[ -r "$F" ] || continue

		(( --N == 0 )) && L=' '

		echo "${2}+- ${F##*/}"

		[ -d "$F" ] && tree "$F" "$2$L  "
	done

	return 0
}

if [ "${BASH_SOURCE[0]}" == "$0" ]
then
	tree "$@"
fi