Last active
February 23, 2024 16:56
-
-
Save antoniocosentino/f2f6d4165fe16bf41d2fa4e0899f7ce8 to your computer and use it in GitHub Desktop.
This bash script receives a local folder as argument and generate a JSON object with the nested tree structure of that directory, including subdirectories and files. I'm then using this data together with rc-tree to visualize my folders in a web application. Sample usage: ./generate_dir_tree.sh /Users/antonio/myDir
This file contains 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
#!/bin/bash | |
if [ $# -ne 1 ]; then | |
echo "Usage: $0 <folder_path>" | |
exit 1 | |
fi | |
generate_id() { | |
echo $(( RANDOM % 1000 + 1 )) | |
} | |
generate_json() { | |
local dir="$1" | |
local id="$2" | |
local json="" | |
local items=("$dir"/*) | |
local count=0 | |
for item in "${items[@]}"; do | |
if [ -d "$item" ]; then | |
if [ $count -gt 0 ]; then | |
json="$json," | |
fi | |
sub_id=$(generate_id) | |
sub_json=$(generate_json "$item" "$sub_id") | |
if [ "$sub_json" != "" ]; then | |
json="$json$sub_json" | |
count=$((count+1)) | |
fi | |
elif [ -f "$item" ]; then | |
if [ $count -gt 0 ]; then | |
json="$json," | |
fi | |
json="$json{\"id\": $(generate_id), \"name\": \"$(basename "$item")\"}" | |
count=$((count+1)) | |
fi | |
done | |
if [ "$json" != "" ]; then | |
json="{\"id\": $id, \"name\": \"$(basename "$dir")\", \"content\": [$json]}" | |
fi | |
echo "$json" | |
} | |
folder_path="$1" | |
output_file="tree_structure.json" | |
main_json=$(generate_json "$folder_path" "$(generate_id)") | |
main_json=$(echo "$main_json" | jq '.content') | |
echo "$main_json" > "$output_file" | |
echo "Tree structure JSON generated and saved to $output_file" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment