Parameter Expansion: Split a Path Without External Tools
MediumShell Scripting15-25 minEvery call to basename, dirname, cut, or sed forks a process — Bash can slice strings itself with parameter expansion, no subprocess required. Your input is in /root/case/assignment.env as PATHSPEC (a full file path).
Write /root/scripts/parse.sh. It takes a path as its first argument and, with no argument, falls back to PATHSPEC from the assignment. Using only parameter expansion, it prints:
`
DIR=<directory part>
BASE=<filename, no directory>
STEM=<filename with its last extension removed>
EXT=<the last extension only>
UPPER=<filename uppercased>
`
The extension is whatever follows the last dot in the filename, so report.2025.tgz has STEM=report.2025 and EXT=tgz.
The tools: ${var%pattern} and ${var%%pattern} strip the shortest and longest matching suffix; ${var#pattern} and ${var##pattern} do the same from the front; ${var^^} uppercases. Working out which one gives which field is the exercise.
Grading runs your script on your PATHSPEC and on a path you haven't seen, so it has to compute the parts, not print them. /root/case/brief.txt restates the task.
- Source the per-session PATHSPEC
- Strip to the directory and to the filename with % and ##
- Remove and isolate the extension
- Uppercase with ${var^^} — all without forking basename/dirname/cut/sed
Hands-on lab: you work on a real Linux box in your browser, graded on the machine's actual state.
