KatInterview

Build a POSIX Shell Script with Validation and Structured Output

StringsModel answer
MediumModel answerStringsshellPOSIXCLI

Last 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 -n for the hostname. The hostname command 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:

CodeCondition
0success
64bad argument count, invalid username, or empty path
65no license derivable from file contents
66file missing, dangling symlink, or not a regular file
71date or uname failed
74I/O error while reading the file
77permission denied
  • All error messages go to stderr.
  • Never use set -e; use explicit || die instead.
  • Use set -u to 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=C for byte-oriented text processing so non-UTF-8 content does not cause awk to misbehave.

Output

  • Use printf '%s %s %s@%s\n' — never pass data as the format string, and prefer printf over echo for portability.

What to deliver

  1. The complete run.sh script.
  2. A brief comment block at the top stating your license-extraction assumption.
  3. 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 sh only — 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.