Is there any linux command that I can call from a Bash script that will print the directory structure in the form of a tree, e.g.,
folder1
a.txt
b.txt
Since I was not too happy with the output of other (non-tree
) answers (see my comment at Hassou's answer), I tried to mimic tree
s output a bit more.
It's similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl
though, but in my case, on the system where I don't have tree
, perl
is available.
ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\// /g;s/^ (\S)/└── \1/;s/(^ | (?= ))/│ /g;s/ (\S)/└── \1/'
Output (shortened):
.
└── fd
└── net
│ └── dev_snmp6
│ └── nfsfs
│ └── rpc
│ │ └── auth.unix.ip
│ └── stat
│ └── vlan
└── ns
└── task
│ └── 1310
│ │ └── net
│ │ │ └── dev_snmp6
│ │ │ └── rpc
│ │ │ │ └── auth.unix.gid
│ │ │ │ └── auth.unix.ip
│ │ │ └── stat
│ │ │ └── vlan
│ │ └── ns
Suggestions to avoid the superfluous vertical lines are welcome :-)
I still like Ben's solution in the comment of Hassou's answer very much, without the (not perfectly correct) lines it's much cleaner. For my use case I additionally removed the global indentation and added the option to also ls
hidden files, like so:
ls -aR | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\// /g'
Output (shortened even more):
.
fd
net
dev_snmp6
nfsfs
rpc
auth.unix.ip
stat
vlan
ns
You can use this one:
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:
.
|-apache2
|---mod_cache_disk
|-apparmor
|-apt
|---archives
|-----partial
|-apt-xapian-index
|---index.1
|-dbconfig-common
|---backups
|-debconf
Source
To add Hassou's solution to your .bashrc, try:
alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/ /'"'"' -e '"'"'s/-/|/'"'"