在CentOS上是否有类似于tree的等效工具?
# yum install tree -y
如果安装不成功,那是因为你没有正确的软件库。我建议使用Dag Wieers的软件库:
http://dag.wieers.com/rpm/FAQ.php#B
之后你就可以进行安装:
# yum install tree -y
现在你已经可以开始使用了。一定要阅读手册页:http://linux.die.net/man/1/tree
以下简单命令将返回一个树形结构:
# tree
您也可以将此输出到文本文件中。还有很多选项..如果您想要除默认输出之外的其他内容,请阅读手册。
# tree > recursive_directory_list.txt
(^^ 在一个文本文件中以便日后查看 ^^)
#!/bin/bash
# only if you have bash 4 in your CentOS system
shopt -s globstar
for file in **/*
do
slash=${file//[^\/]}
case "${#slash}" in
0) echo "|-- ${file}";;
1) echo "| |-- ${file}";;
2) echo "| | |-- ${file}";;
esac
done
由于在CentOS中默认没有安装tree
,因此...
[user@CentOS test]$ tree
-bash: tree: command not found
[user@CentOS test]$
你也可以使用以下ls
命令生成几乎相似的tree
输出结果
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
例子:
[user@CentOS test]$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
.
|-directory1
|-directory2
|-directory3
[user@CentOS directory]$
正如您在此处所看到的那样,CentOS默认情况下没有安装tree,因此您需要查找一个RPM并手动安装它。
# yum list tree
Available Packages
tree.i386 1.5.0-4 base
安装它:
yum install tree
我需要在一台不允许我使用yum
安装的远程计算机上工作。因此,我修改了bash-o-logist的答案,以获得更灵活的解决方案。
它接受一个(可选)参数,即您想要显示的子目录的最大级别。将其添加到您的$PATH
中,享受一个无需安装的tree
命令。
我不是shell专家(为了编写这个非常简短的脚本,我不得不Google很多次)。所以如果我做错了什么,请告诉我。非常感谢!
#!/bin/bash
# only if you have bash 4 in your CentOS system
shopt -s globstar # enable double star
max_level=${1:-10}
for file in **
do
# Get just the folder or filename
IFS='/'
read -ra ADDR <<< "$file"
last_field=${ADDR[-1]}
IFS=' '
# Get the number of slashes
slash=${file//[^\/]}
# print folder or file with correct number of leadings
if [ ${#slash} -lt $max_level ]
then
spaces=" "
leading=""
if [ "${#slash}" -gt 0 ]
then
leading=`eval $(echo printf '"|${spaces}%0.s"' {1..${#slash}})`
fi
echo "${leading}|-- $last_field"
fi
done