Last active
July 4, 2024 10:05
-
-
Save takuzoo3868/65b0940747175301854000ce7e0b96b7 to your computer and use it in GitHub Desktop.
Shell script that reproduced the tree command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# treeを擬似的に再現したスクリプト | |
dir_count=0 | |
file_count=0 | |
traverse() { | |
dir_count=$(expr $dir_count + 1) | |
local directory=$1 | |
local prefix=$2 | |
local children=($(ls $directory)) | |
local child_count=${#children[@]} | |
for idx in "${!children[@]}"; do | |
local child="${children[$idx]}" | |
local child_prefix="│ " | |
local pointer="├── " | |
if [ $idx -eq $(expr ${#children[@]} - 1) ]; then | |
pointer="└── " | |
child_prefix=" " | |
fi | |
echo "${prefix}${pointer}$child" | |
[ -d "$directory/$child" ] && | |
traverse "$directory/$child" "${prefix}$child_prefix" || | |
file_count=$(expr $file_count + 1) | |
done | |
} | |
root="." | |
[ "$#" -ne 0 ] && root="$1" | |
echo $root | |
traverse $root "" | |
echo | |
echo "$(expr $dir_count - 1) directories, $file_count files" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, @Vouze! Just updated this script to show trailing backslash for folders, not to print strange tail if the directory is empty, and colored folders and executable files in the tree: