$_ CLI In Depth
Learning progress 0%
Build · Terminal, Shell & Kernel

Build: A Command Explainer Script

Write /workspace/explain, a script that reports what kind of command each name is.

~40 min Beginner 3 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: An executable script

Create explain in /workspace with a #!/usr/bin/env bash shebang and make it executable with chmod +x explain.

Step 2: Report the kind

For every name given, ./explain prints a line that includes the name and its kind from type -t. For files, include the path from command -v.

Try ./explain cd ls printf '[['.

Step 3: A meaningful exit status

./explain exits 0 when every name was found and 1 when any name was not. Try ./explain ls nosuchcmd; echo $?.

Files

  • explain: 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.

explain

BASH23 lines
#!/usr/bin/env bash
# explain: report what each command name resolves to.
set -u

status=0
for name in "$@"; do
  kind=$(type -t -- "$name")
  case $kind in
    '')
      echo "$name: not found"
      status=1
      ;;
    file)
      path=$(command -v -- "$name")
      echo "$name: file $path"
      file -L "$path"
      ;;
    *)
      echo "$name: $kind"
      ;;
  esac
done
exit "$status"

walkthrough.sh

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

# Step 1: An executable script
cat > explain <<&#039;EOF&#039;
#!/usr/bin/env bash
# explain: report what each command name resolves to.
set -u

status=0
for name in "$@"; do
  kind=$(type -t -- "$name")
  case $kind in
    &#039;&#039;)
      echo "$name: not found"
      status=1
      ;;
    file)
      path=$(command -v -- "$name")
      echo "$name: file $path"
      file -L "$path"
      ;;
    *)
      echo "$name: $kind"
      ;;
  esac
done
exit "$status"
EOF
chmod +x explain

# Step 2: Report the kind
true

# Step 3: A meaningful exit status
true

Lessons this build uses