Build a POSIX Shell Script with Validation and Structured Output
StringsModel answerLast updated
Write a strict POSIX sh script that validates arguments, reads a file, extracts a license string, and prints a formatted timestamped line.
Task
Write a POSIX-compliant shell script called run.sh that is invoked as:
./run.sh <username> <filepath>
It must print exactly one line to stdout in this format:
<timestamp> <license> <user@hostname>
where:
<timestamp>is the current UTC time in ISO 8601 format:YYYY-MM-DDThh:mm:ssZ<license>is a string derived from the contents of the file at<filepath>(see below)<user@hostname>is the provided username combined with the machine's hostname
Requirements
Argument parsing and validation
- The script must accept exactly two positional arguments. Any other count is a usage error.
- The username must be non-empty and contain only alphanumeric characters, dots, underscores, or hyphens. It must not begin with a hyphen.
- The filepath must be non-empty.
File validation
- The file must exist, be a regular file (not a directory or symlink target that is missing), and be readable.
- Distinguish between "file not found", "not a regular file", and "permission denied" in both the error message and the exit code.
License extraction
- State your assumption about the format and document it in a comment.
- A reasonable default: look for the first line matching
License: <value>(case-insensitive, leading whitespace allowed). Use the trimmed value after the colon as the license string. - If no such header exists, fall back to the first whitespace-delimited token of the first non-blank line.
- If the file is empty or contains only blank lines, that is a data error.
- Strip trailing carriage returns so the script handles CRLF files correctly.
Timestamp and hostname
- Use
date -u '+%Y-%m-%dT%H:%M:%SZ'for the timestamp. This is POSIX-specified. - Use
uname -nfor the hostname. Thehostnamecommand is not guaranteed to exist in a strict POSIX environment.
Error handling and exit codes
Use distinct exit codes for each failure class. The BSD sysexits.h convention is widely recognized:
| Code | Condition |
|---|---|
| 0 | success |
| 64 | bad argument count, invalid username, or empty path |
| 65 | no license derivable from file contents |
| 66 | file missing, dangling symlink, or not a regular file |
| 71 | date or uname failed |
| 74 | I/O error while reading the file |
| 77 | permission denied |
- All error messages go to stderr.
- Never use
set -e; use explicit|| dieinstead. - Use
set -uto catch unset variables.
Non-ASCII and special paths
- Paths are byte strings in POSIX. Quoting every expansion handles spaces and most special characters.
- Paths beginning with
-must be rewritten as./-…before being passed to utilities, to prevent them from being interpreted as flags. - Use
LC_ALL=Cfor byte-oriented text processing so non-UTF-8 content does not causeawkto misbehave.
Output
- Use
printf '%s %s %s@%s\n'— never pass data as the format string, and preferprintfoverechofor portability.
What to deliver
- The complete
run.shscript. - A brief comment block at the top stating your license-extraction assumption.
- A short test outline covering: happy path, wrong argument count, invalid username, missing file, unreadable file, empty file, CRLF file, and a path starting with
-.
Constraints
- POSIX
shonly — no bash, ksh, or zsh extensions. - No external tools beyond
awk,date,uname,printf, and standard POSIX utilities. - The output must be exactly one line on success.
Hints
Hint 1
Model the script as a pipeline of validated stages: args → file checks → license extraction → system calls → output. Each stage either produces a value or calls die() with a specific exit code. This keeps the control flow linear and easy to audit.
Hint 2
awk is the right tool for license extraction because it handles the License: header search, CR stripping, and first-token fallback in one pass. Set LC_ALL=C before the command substitution so non-UTF-8 bytes in the file do not cause awk to fail silently or truncate output.
Hint 3
There is an unavoidable TOCTOU race between [ -r "$file" ] and the awk read. The pre-checks exist to produce human-readable error messages; the || die on the command substitution is the actual safety net. Mention this explicitly — interviewers reward awareness of it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The script is a sequence of validated stages. Each one either produces a named value or exits immediately with a specific code and a message on stderr. There are no algorithms to design — the challenge is defensive engineering: quoting, exit-code discipline, explicit assumptions, and awareness of edge cases.
Stage 1 — Argument validation
Require exactly two arguments. Validate the username with a case pattern rather than a separate utility — portable and dependency-free. Rewrite any filepath that starts with - to ./-… immediately, before it ever reaches another utility.
[ "$#" -eq 2 ] || usage
user=$1; file=$2
[ -n "$user" ] || die "$EX_USAGE" "username must not be empty"
case $user in
-*) die "$EX_USAGE" "username starts with -" ;;
*[!A-Za-z0-9._-]*) die "$EX_USAGE" "invalid username: $user" ;;
esac
[ -n "$file" ] || die "$EX_USAGE" "filepath must not be empty"
case $file in -*) file=./$file ;; esac
Stage 2 — File checks
Order matters: test existence first, then type, then readability. This gives the most specific error message for each failure. The two-step existence check (-e after -L) catches dangling symlinks, which [ ! -e ] alone misses.
[ -e "$file" ] || [ -L "$file" ] || die "$EX_NOINPUT" "no such file: $file"
[ -e "$file" ] || die "$EX_NOINPUT" "dangling symlink: $file"
[ -f "$file" ] || die "$EX_NOINPUT" "not a regular file: $file"
[ -r "$file" ] || die "$EX_NOPERM" "permission denied: $file"
There is an inherent TOCTOU window between these checks and the actual read. The || die on the awk command substitution covers that race; the pre-checks exist only to give readable diagnostics.
Stage 3 — License extraction
The assumption must be stated in a comment. Here: the first line matching License: <value> (case-insensitive, leading whitespace allowed) wins. If no such header exists, the first token of the first non-blank line is the fallback. CR is stripped from every line so CRLF files work transparently.
LC_ALL=C makes awk treat the file as a byte stream. Without it, a non-UTF-8 byte sequence could cause some awk implementations to misbehave.
license=$(LC_ALL=C awk '
{ sub(/\r$/, "") }
!seen && NF { seen = 1; first = $1 }
tolower($0) ~ /^[ \t]*license:/ {
v = $0
sub(/^[ \t]*[^:]*:[ \t]*/, "", v)
sub(/[ \t]+$/, "", v)
if (v != "") { print v; found = 1; exit }
}
END { if (!found && seen) print first }
' "$file") || die "$EX_IOERR" "failed to read: $file"
[ -n "$license" ] || die "$EX_DATAERR" "no license found in: $file"
Stages 4 & 5 — Timestamp and hostname
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ') || die "$EX_OSERR" "date failed"
host=$(uname -n) || die "$EX_OSERR" "uname failed"
[ -n "$host" ] || die "$EX_OSERR" "empty hostname"
uname -n is POSIX. hostname is not — avoid it.
Stage 6 — Output
printf '%s %s %s@%s\n' "$ts" "$license" "$user" "$host"
printf with %s is safe regardless of what characters appear in the values. Never use echo for data — it interprets \n, -n, and similar sequences differently across shells.
Complete script
#!/bin/sh
# Usage: ./run.sh <username> <filepath>
# Output: <ISO8601-UTC> <license> <user@hostname>
#
# License assumption: the first line matching "License: <value>"
# (case-insensitive, leading whitespace allowed) is used. The value
# is trimmed and CR-stripped. Fallback: first token of first non-blank line.
set -u
EX_USAGE=64; EX_DATAERR=65; EX_NOINPUT=66
EX_OSERR=71; EX_IOERR=74; EX_NOPERM=77
prog=${0##*/}
die() { code=$1; shift; printf '%s: %s\n' "$prog" "$*" >&2; exit "$code"; }
usage() { printf 'usage: %s <username> <filepath>\n' "$prog" >&2; exit "$EX_USAGE"; }
# -- 1. arguments
[ "$#" -eq 2 ] || usage
user=$1; file=$2
[ -n "$user" ] || die "$EX_USAGE" "username must not be empty"
case $user in
-*) die "$EX_USAGE" "username starts with -" ;;
*[!A-Za-z0-9._-]*) die "$EX_USAGE" "invalid username: $user" ;;
esac
[ -n "$file" ] || die "$EX_USAGE" "filepath must not be empty"
case $file in -*) file=./$file ;; esac
# -- 2. file checks
[ -e "$file" ] || [ -L "$file" ] || die "$EX_NOINPUT" "no such file: $file"
[ -e "$file" ] || die "$EX_NOINPUT" "dangling symlink: $file"
[ -f "$file" ] || die "$EX_NOINPUT" "not a regular file: $file"
[ -r "$file" ] || die "$EX_NOPERM" "permission denied: $file"
# -- 3. license
license=$(LC_ALL=C awk '
{ sub(/\r$/, "") }
!seen && NF { seen = 1; first = $1 }
tolower($0) ~ /^[ \t]*license:/ {
v = $0
sub(/^[ \t]*[^:]*:[ \t]*/, "", v)
sub(/[ \t]+$/, "", v)
if (v != "") { print v; found = 1; exit }
}
END { if (!found && seen) print first }
' "$file") || die "$EX_IOERR" "failed to read: $file"
[ -n "$license" ] || die "$EX_DATAERR" "no license found in: $file"
# -- 4/5. timestamp and hostname
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ') || die "$EX_OSERR" "date failed"
host=$(uname -n) || die "$EX_OSERR" "uname failed"
[ -n "$host" ] || die "$EX_OSERR" "empty hostname"
# -- 6. output
printf '%s %s %s@%s\n' "$ts" "$license" "$user" "$host"
exit 0
Complexity
- Time: O(n) in file size in the worst case (no header found).
awkexits early when it finds the header. - Space: O(1) — only the current line and extracted value are held in memory.
Edge cases and expected behavior
| Input | Exit | Note |
|---|---|---|
| Wrong argument count | 64 | usage message to stderr |
Username "" or bad user! | 64 | validation rejects it |
| Missing file | 66 | |
| Directory passed as filepath | 66 | -f check fails |
Unreadable file (chmod 000) | 77 | |
| Empty or blank-only file | 65 | awk prints nothing |
License: MIT\r in CRLF file | 0 | output contains MIT |
license: Apache-2.0 | 0 | trimmed to Apache-2.0 |
No header, first line GPL-3.0 … | 0 | fallback gives GPL-3.0 |
Path ./données/café.txt | 0 | byte-string quoting handles it |
Path -weird-name | 0 | rewritten to ./-weird-name |
Common mistakes
- Using
set -e— its semantics inside$()and&&/||chains are surprising and implementation-dependent. Explicit|| dieis clearer and portable. - Using
echofor output —echointerprets\n,-n, and similar sequences differently between/bin/shimplementations.printf '%s'is unambiguous. - Passing data as the
printfformat string — a license or path containing%swould corrupt output or cause an error. - Using
hostnameinstead ofuname -n—hostnameis not specified by POSIX. - Skipping the TOCTOU disclosure — the gap between
[ -r ]and the actual read is real. Mentioning it signals systems awareness even though it cannot be fully closed in a shell script. - Missing the ambiguity discussion — a license value like
MIT OR Apache-2.0contains a space, making the output line ambiguous if a consumer splits on whitespace. Pick a resolution (keep as-is, first token only, or replace spaces with_) and explain the trade-off.