Safe file batching: NUL delimiters and filename boundary tests
Files exported by a business application may copy correctly by hand, yet go missing, overwrite files with matching names, or trigger “unrecognized option” errors when a nightly script handles them. The disk is not necessarily at fault. Spaces, newlines, asterisks, and leading hyphens in filenames can change how the shell interprets arguments. Before running archive, verification, or handoff jobs on a dedicated server against real data, verify that one filename always becomes exactly one argument.
The following exercise uses Bash, GNU find, GNU coreutils, and Python 3 on Debian 12 to build an isolated fixture and verify the copied results. Connection credentials for your IronSSH server are available in the console after payment. Once connected over SSH, you can complete the exercise with a regular user account; no changes to system services are needed.
1. Understand the three boundaries between filenames and arguments
Linux filenames cannot contain a NUL byte, and individual path components cannot contain a slash. They can, however, contain newlines. That makes “one file per line” unsuitable as a general-purpose machine interface. The output of ls is for people to browse, not for batch jobs to consume.
A common mistake is for f in $(find ...): the output of command substitution is then subject to word splitting and pathname expansion. Even if you double-quote the variable inside the loop, the input has already been damaged before the loop starts. Switching to a line-reading loop only solves the whitespace problem for spaces; it still splits names that contain newlines.
Three boundaries need separate protection: delimit records with NUL during enumeration, preserve each record exactly when reading it, and double-quote variables when invoking commands, adding -- to end option parsing wherever the command supports it. None of these measures replaces the others.
This article only covers a test directory that you create yourself and stop writing to. NUL delimiters do not lock a directory or prevent another process from replacing files after enumeration. Do not treat this example as a secure implementation for handling directories subject to malicious concurrent changes.
2. Build an isolated fixture with unusual filenames
Run the following code in the same Bash session. The temporary directory is only for this experiment. Inputs and outputs are kept separate, and the manifest lives outside the input directory so that it cannot be enumerated while it is being generated.
lab=$(mktemp -d)
export LAB="$lab"
mkdir -- "$LAB/in" "$LAB/out"
python3 - <<'PY'
import os
from pathlib import Path
root = Path(os.environ["LAB"])
names = [
"plain.txt",
"two words.txt",
"line\nbreak.txt",
"-rf",
"*.txt",
"中文数据.txt",
]
for index, name in enumerate(names):
(root / "in" / name).write_bytes(
f"fixture-{index}\n".encode("utf-8")
)
(root / "outside.txt").write_bytes(b"outside\n")
(root / "in" / "outside-link").symlink_to(root / "outside.txt")
print(root)
PY
Each of the six regular files has different contents, making mismatched file-to-content mappings and overwrites easier to detect. The symbolic link tests the selection boundary: this exercise copies only regular files directly inside the input directory. It does not recurse, follow links, or include the contents of a link target in the set of files to be delivered.
To inspect the names manually, run printf '%q\n' ./* in the input directory. Bash’s %q escapes characters such as newlines, producing a clearer display than printing filenames directly. This output is evidence for a person to inspect, not a command to execute next, and it should never be passed to eval.
3. Use a NUL-delimited manifest for controlled copying
Generate the manifest first, check the command’s result, and only then read the manifest. This example deliberately avoids putting find in a process substitution. Running enumeration separately makes failures at that stage easier to detect and helps prevent partial results from being mistaken for a completed job.
find -P "$LAB/in" -maxdepth 1 -type f -print0 \
> "$LAB/manifest0"
After confirming that the previous command exited with status zero, run:
(
set -e
count=0
while IFS= read -r -d '' file; do
cp -P -- "$file" "$LAB/out/"
count=$((count + 1))
done < "$LAB/manifest0"
printf 'copied=%s\n' "$count"
test "$count" -eq 6
)
IFS= prevents leading and trailing whitespace from being trimmed, -r disables backslash interpretation, and Bash’s -d '' uses NUL as the record terminator. Double quotes ensure that each path is passed as one argument, while -- explicitly ends the option portion of the cp command.
The source paths in this example are absolute, so a leading hyphen in a filename cannot appear at the start of the full argument. Even so, -- is retained to make the invocation boundary explicit. cp -P does not dereference source symbolic links, but it does not eliminate every risk of concurrent file replacement.
Because the job only handles files directly inside one directory, each name is unique and can be copied straight into a single output directory. If you change this to a recursive traversal, you cannot keep only the basename: files with the same name in different subdirectories would overwrite one another. Preserve the relative directory structure or explicitly reject collisions.
4. Verify both the file set and the contents
A message saying “six files copied” proves only that the loop ran six times. It does not prove that the result is correct. Verification should cover at least the set of names, object types, and file contents. Comparing total byte counts alone is insufficient: swapping the contents of two files can leave the total unchanged.
python3 - <<'PY'
import json
import os
from pathlib import Path
root = Path(os.environ["LAB"])
src = root / "in"
dst = root / "out"
expected = {
p.name for p in src.iterdir()
if p.is_file() and not p.is_symlink()
}
actual = {p.name for p in dst.iterdir()}
if actual != expected:
raise SystemExit("File set mismatch")
for name in sorted(expected):
target = dst / name
if target.is_symlink() or not target.is_file():
raise SystemExit("Unexpected target type")
if (src / name).read_bytes() != target.read_bytes():
raise SystemExit("Content mismatch")
print(json.dumps(
{"verified": len(expected), "names": sorted(expected)},
ensure_ascii=True
))
PY
On success, the output should be JSON with verified set to 6. Newlines appear as escape sequences inside strings, so they cannot create forged log lines. Do not concatenate raw filenames directly into multiline alerts: a single name containing a newline could look like multiple events.
This fixture uses small files, so reading them directly into memory makes comparison straightforward. For large production files, switch to chunked reads or streaming hashes rather than loading entire files into memory. The source directory must also remain stable; otherwise, a copied file differing from the current source could be the result of a legitimate change made after the copy finished.
5. Add negative tests and production checks
First, prove that errors can be detected
Delete one output file and rerun the verification program; it should report a file-set mismatch. Restore the complete copy, then change the contents of one output file; it should report a content mismatch. You can also replace an output file with a symbolic link and confirm that the object-type check rejects it. Inject only one fault at a time so that an earlier error does not mask a later check.
These tests matter more than demonstrating one successful copy. The verification program itself might check only counts, or inadvertently follow a link back to the original file, creating a circular process in which an incorrect result is used to validate another incorrect result.
Apply the findings to production scripts
Production jobs should record the input root directory, selection criteria, manifest-generation status, successful processing count, and failure status. Keep old results out of the output directory. If you reuse a directory, define a separate policy for handling old files rather than relying on overwrites to perform an implicit cleanup.
For large batches, consider find -exec ... {} +. It lets the tool assemble arguments directly and reduces the overhead of starting a process for every file. Do not return to text concatenation for speed, and do not store a NUL-delimited manifest in a shell variable: variables cannot reliably hold NUL bytes.
Finally, define the concurrency boundary. Pause the export program before processing a stable directory, or read from a stable snapshot. If an untrusted account is continuously writing to the directory, quoting, --, and find -P are not enough. A dedicated implementation is needed to locate entries relative to directory file descriptors, restrict link following, and verify opened objects. Keep the fixture and verification program, and rerun the full set of positive and negative tests whenever you change traversal depth, parallelism, or the copying tool.
Frequently asked questions
Is quoting a filename variable enough?
No. Quoting prevents word splitting and wildcard expansion, but cannot repair a list already split on newlines or replace the -- option terminator supported by a command. Preserve filename boundaries during enumeration, reading, and execution.
Does a NUL manifest prevent files from being replaced during a batch?
No. NUL separates records; it does not lock directory entries or file contents. For untrusted directories with concurrent writers, stop writes, use a stable snapshot, or implement descriptor-relative file access.
AMD EPYC 7543P Dedicated Server
From $444.5/month