stat counter
Castor Vs Granulated Sugar
Here's a bash script that finds a node's depth by walking upward to the root, assuming a `parent_id child_id` pairs file (lines with parent–child relationships): ```bash #!/bin/bash # Usage: ./depth.sh # Format assumed: each line is "parent_id child_id" FILE="$1" TARGET="$2" if [ -z "$FILE" ] || [ -z "$TARGET" ]; then echo "Usage: $0 " echo " pairs_file: lines formatted as 'parent_id child_id'" exit 1 fi if [ ! -f "$FILE" ]; then echo "Error: File '$FILE' not found." exit 1 fi depth=0 current="$TARGET" while true; do # Look up parent of the current node parent=$(awk -v child="$current" '$2 == child {print $1; exit}' "$FILE") if [ -z "$parent" ]; then break fi depth=$((depth + 1)) current="$parent" done echo "Depth of node '$TARGET': $depth" ``` ### How it works | Step | What it does | |------|-------------| | 1 | Reads the pairs file line by line with `awk` | | 2 | Finds the parent of the current node | | 3 | Increments the depth counter | | 4 | Moves up to the parent and repeats | | 5 | Stops when no parent is found (i.e., we reached the root) | ### Example Given a file `tree.txt`: ``` 0 1 0 2 1 3 1 4 3 5 ``` Running: ```bash ./depth.sh tree.txt 5 ``` Output: ``` Depth of node '5': 3 ``` Path: `5 → 3 → 1 → 0` (three edges from the root). If the node is the root itself (`0`), the script returns depth 0.