$_ CLI In Depth
Learning progress 0%
Build · Filesystem Navigation & Inodes

Build: A tree Clone in Bash

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

~30 min Beginner 2 checked steps

Build it on a real Linux machine

The guided lab boots Linux in your browser. Each step runs a check script on that machine, so it passes only when your files and output are right.

What you will build

Step 1: Create the sample tree

Create this tree under /workspace: a.txt at the top, sub/b.txt, and sub/deeper/c.txt:

BASH5 lines
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

Step 2: 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

Files

  • mytree.sh: the finished script.
  • walkthrough.sh: every step of the reference solution, in order.

How it is checked

Each step in the guided lab has a check script that runs on the lab machine after you finish. It passes only when the files and output it expects are there, so the lab cannot be completed by reading alone.

Reference files

Read these after you have tried the lab. They are the solutions the checks were verified against.

mytree.sh

BASH17 lines
#!/usr/bin/env bash
set -eu
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=$(basename "$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

walkthrough.sh

BASH32 lines
#!/usr/bin/env bash
# Reference solution for every step of the guided lab, in order.

# Step 1: Create the sample tree
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

# Step 2: Write mytree.sh
cd /workspace
cat > mytree.sh <<&#039;EOF&#039;
#!/usr/bin/env bash
set -eu
walk() {
  local dir=$1 depth=$2 entry name indent
  indent=$(printf &#039;%*s&#039; $((depth * 2)) &#039;&#039;)
  for entry in "$dir"/*; do
    [ -e "$entry" ] || [ -L "$entry" ] || continue
    name=$(basename "$entry")
    if [ -d "$entry" ] && [ ! -L "$entry" ]; then
      printf &#039;%s%s/\n&#039; "$indent" "$name"
      walk "$entry" $((depth + 1))
    else
      printf &#039;%s%s\n&#039; "$indent" "$name"
    fi
  done
}
walk "$1" 0
EOF
bash mytree.sh sample > /dev/null

Lessons this build uses