$_ CLI In Depth
Learning progress 0%
build filesystem inodes navigation

Build: A tree Clone in Bash

5 min read Module 2: Filesystem Navigation & Inodes Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:17

The specification

Write a script named /workspace/mytree.sh. It takes exactly one argument, a directory, and prints every entry under that directory as an indented listing. The rules are short. Each level of nesting adds two spaces of indentation. Entries in a directory are printed in sorted order by name. A subdirectory is printed with a trailing slash, and its contents follow it, indented one level further. Hidden entries whose names start with a dot are skipped. Symbolic links are printed by name and are not followed, even when they point at a directory. If the number of arguments is wrong, the script prints a usage line to standard error and exits with status 2.

For the sample tree that the lab creates, the expected output has five lines. The file a.txt comes first, then the directory sub/, which contains b.txt and a deeper directory deeper/ holding c.txt. The output must match exactly, including the spacing, because the checker compares the text.

Start with the loop

The core of the script is a loop over the entries in a directory. The shell glob "$dir"/* expands to the names in sorted order, and it omits names that start with a dot, which is the behavior the specification asks for. The loop must also handle an empty directory, where the glob does not match and the literal pattern is passed through. Testing that the entry exists, or that it is a symbolic link, handles that case cleanly.

Inside the loop, use basename or parameter expansion to strip the directory part from the name. Parameter expansion with ##*/ is faster and does not start another program. Then decide whether the entry is a real directory. The test -d follows symbolic links, so the test for a real directory must also check -L and reject links.

Recurse with a function

A recursive function is the natural fit. The function takes two arguments, the directory to walk and the current depth. It computes the indentation as a string of spaces with printf and a width specifier, then prints each entry. When an entry is a real directory, the function prints the name with a slash and calls itself with one more level of depth. Local variables keep the recursion from overwriting the outer loop's state, which is the reason for the local declaration in the reference solution.

Checking your work

Make the sample tree with the commands in the first lab step, then run the script with that tree as the argument. Compare the output with the expected listing in the lab. If a line is missing, check the glob and the empty directory case. If the order is wrong, check whether you sorted by the glob or by a command that uses a different collation. If a symbolic link is followed and its contents appear, the real-directory test is wrong.

Common mistakes to watch for

The first common mistake is forgetting that the glob omits hidden names, so a directory that contains only hidden files prints nothing. That may be correct under the specification, but it is worth noticing. The second is printing the top-level directory name in the listing. The specification asks for the entries inside the argument, not the argument itself, so the first loop must start from the contents.

The third mistake is building the indentation with a loop that appends spaces one at a time. It works, but it is slower and harder to read than a single printf with a width. The fourth is forgetting to quote the path in the glob. A directory name with a space in it breaks an unquoted expansion, and the quotes around the variable are what keep the walk correct. Test your script on a directory whose name contains a space before you consider it finished.

Finally, notice that the recursion depth is limited only by the length of the paths the kernel accepts. For a deep tree, the function could hit that limit, but for the sample tree in the lab, the depth is three and there is no concern.

Reference solution

The reference solution is short and uses only the shell builtins it needs. Read it after you have written your own version, and compare the choices. In particular, notice how the link test comes before the directory test, and how the function passes its depth as a plain integer.

BASH21 lines
#!/usr/bin/env bash
# mytree.sh DIR: print a tree-like listing of DIR, sorted, without following links
set -eu
[ $# -eq 1 ] || { echo "usage: mytree.sh DIR" >&2; exit 2; }

walk() {
  local dir=$1 depth=$2 entry name indent
  indent=$(printf '%*s' $((depth * 2)) '')
  for entry in "$dir"/*; do
    [ -e "$entry" ] || [ -L "$entry" ] || continue
    name=${entry##*/}
    if [ -d "$entry" ] && [ ! -L "$entry" ]; then
      printf '%s%s/\n' "$indent" "$name"
      walk "$entry" $((depth + 1))
    else
      printf '%s%s\n' "$indent" "$name"
    fi
  done
}

walk "$1" 0

The script runs as a normal program. Make it executable with chmod if you want to run it by name, but the lab runs it with bash so the permission bits are not needed for the check.

Extensions to try

Once the basic version works, try adding a depth limit as an optional second argument, or print a count of entries at the end. Each extension teaches a different skill. A depth limit makes you thread a value through the recursion, and a count makes you think about where state should live. Keep the script under thirty lines even as you extend it, which is a good sign that the design is clear.

Visualizer

A directory is a list of (name, inode number) pairs. The inode holds the file itself. Hard links add names; symlinks store a path.

1 / 5
directory /workspace
nameinode
a1201
inode table
inodetypelinksdata
1201regular1"hi\n"

echo hi > a allocates inode 1201 and adds the entry a → 1201 to the directory. The link count is 1.

cd /workspace; echo hi > a; ln a b; ls -li a b; rm a; cat b; stat -c "%h links" b
Terminal lab · 2 steps · real Linux in your browser

Build mytree.sh step by step

Create a sample tree, then write a script that prints it with indentation and sorted entries.

01
Create the sample tree
Create this tree under /workspace: a.txt at the top, sub/b.txt, and sub/deeper/c.txt: ``bash cd /workspace mkdir -p sample/sub/deeper echo one > sample/a.txt echo two > sample/sub/b.txt echo three > sample/sub/deeper/c.txt ``
Show hint for step 1
mkdir -p creates the nested directories in one command.
02
Write mytree.sh
Write /workspace/mytree.sh. It takes one directory argument and prints the entries under it. Sort them, indent each level by two spaces, add a slash after each directory, skip names that start with a dot, and recurse into directories that are not symbolic links. Start with a for loop over the directory glob, then move the loop into a function that takes a depth argument. Run it with: bash mytree.sh sample
Show hint for step 2
Test -L before -d so a symbolic link is printed by name and never followed. Pass depth + 1 when you recurse.
Check yourself Question 1 of 4
Concept Check Symbolic links in the spec recall

According to the specification, how is a symbolic link printed by mytree.sh?

Recap & Key Takeaways

A tree-like listing is a recursive walk over sorted directory entries, with indentation that grows by one level per directory.
Testing with -L before -d keeps a symbolic link from being followed and listed as a directory.
The glob that expands a directory returns names in sorted order and skips names that start with a dot.
Use local variables inside a recursive function so each call has its own state.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue