Compose safe file and path commands
Paths are data, not shell code. A relative path starts from the current directory; an absolute path starts at /. Quote each path expansion to preserve spaces, wildcard characters and empty arguments. Quoting does not stop a leading hyphen from being interpreted as an option: use -- with utilities that support it, or a ./ prefix for relative names. basename and dirname perform lexical path operations, not existence checks. cp copies data and mv moves or renames; both can overwrite existing destinations. Use a fresh practice directory and inspect the destination first. The examples create only synthetic files. The fresh directory is a precondition, not an overwrite safeguard. Stop when fixture creation or copying fails; quoting does not guarantee that a path exists.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Inspect path components
path='reports/daily report.txt'basename -- "$path"dirname -- "$path"Expected stdout:
daily report.txtreportsThe path need not exist. basename selects the final component; dirname selects the directory portion.
Copy a filename with a leading hyphen
printf 'notes\n' > './-draft notes.txt' || exit 1cp -- '-draft notes.txt' 'copy notes.txt' || exit 1cat -- 'copy notes.txt'Expected stdout:
notesQuoting preserves spaces and -- terminates option parsing for cp.
Rename inside a fixture
mkdir -- reports || exit 1printf 'ready\n' > reports/draft.txt || exit 1mv -- reports/draft.txt 'reports/final report.txt' || exit 1cat -- 'reports/final report.txt'Expected stdout:
readyThe old name disappears and the new name holds the original data. Use a new destination.
Common mistakes
Never concatenate a shell command string from a filename. Do not parse ls output or assume a quoted -name is a safe operand. Avoid overwriting real files during practice.
Practice
Create a new directory containing a file named -draft notes.txt. Copy it to a new name, print its contents, then explain both the quoting and the option terminator. Do not modify an existing file.
Next: Find and pass filenames safely