CodeRigor

FREE LESSON

Files, pathnames & safe tool arguments

Handle filenames as data, use redirection and option terminators, and avoid parsing ls output.

Before this lesson, complete bash-functions.

This course runs GNU Bash with ordinary GNU text tools in a fresh Linux sandbox.

A pathname is a string passed to a file API, not a line of ls output. Valid Unix path components can contain spaces, tabs, newlines and glob characters. Preserve one pathname per argument with quoted expansions and arrays. Do not split a printed directory listing to rediscover names. When a traversal is needed, choose a null-delimited interface instead of a newline-delimited one.

Literal path handling
start / 3
Literal path handling

Apply the contract

Quoting preserves argument boundaries but does not stop a program from interpreting a leading dash as an option. Many tools accept -- to end options. Input redirection is another useful interface: wc -c < "$file" opens the file in the shell and passes its bytes on stdin, so wc prints only the byte count and never interprets the filename. In this form a name such as -n is ordinary file data to the shell's redirection.

Count through stdin
start / 3
Count through stdin
Bash
file='two words.txt'
printf 'abc\n' > "$file"
wc -c < "$file"
rm -- "$file"

Reason about the edge cases

Use [[ -f $file ]] when the contract asks for a regular file, and handle a missing path explicitly. Byte counts differ from character counts for multibyte text; this lesson asks for bytes. Command substitution captures stdout and removes trailing newlines, which suits a numeric count but is not a general way to preserve arbitrary file contents. The fixtures also verify that input files survive unchanged. A solution that truncates an input while trying to count it violates the contract even if its displayed number happens to look reasonable.

Preserve input state
start / 3
Preserve input state

Practice

For every argument naming a regular fixture file, print its byte count. Otherwise print missing. Preserve argument order and leave every input file unchanged. Paths can contain spaces, newlines, glob characters, command-substitution-looking text, or a leading dash. Do not interpret filenames as shell code or as tool options.

Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Free shell scripting foundation. Use the authored lesson and GNU Bash manual for this lab’s precise argument, status and process contract.