2.3 Safely Operating Files
Prerequisites: Current Directory and Paths Estimated time: 12 minutes Practice environment: Bash/Zsh and common Unix commands; all changes occur in a temporary directory You are ready to continue when: you can create, view, copy, move, and safely delete files
After confirming the current directory, begin modifying files inside a disposable practice area. Copying, renaming, and deletion all happen there, without touching the home directory or a real project.
Create a Practice Area
workdir=$(mktemp -d)
cd "$workdir"
mkdir -p project/{src,test,docs}
touch project/README.mdtouch creates an empty file if the file does not exist; if the file already exists, it updates its timestamp without clearing its contents.
Writing and Reading
printf '%s\n' 'Hello Workshop!' > project/README.md
printf '%s\n' 'Second line' >> project/README.md
cat project/README.md
head -n 1 project/README.md>creates or overwrites the target file.>>appends content to the end of the file.catis suitable for short texts; for large files, uselessto paginate and view content efficiently.
The escaping behavior and option handling of echo can vary across implementations. When scripts require precise output, prefer using printf.
Copy, Move, and Rename
cp project/README.md project/docs/README.copy.md
mv project/docs/README.copy.md project/docs/guide.md
cp -R project/docs project/docs-backup
find . -printmv can both move and rename files. cp -R recursively copies directories, but handling of metadata, links, and extended attributes varies by option and platform, and should not be used as a substitute for formal backup tools.
Spaces and Files with Hyphen Prefixes
touch 'project/My Important File.txt'
touch 'project/-draft'
ls -l -- 'project/My Important File.txt' 'project/-draft'
rm -- 'project/My Important File.txt'
rm -- 'project/-draft'touch My Important File.txt treats spaces as argument separators, creating three separate files. Quoting the entire path preserves the spaces. -- ends option parsing when a name such as -draft is passed directly. The path project/-draft used here already starts with a directory name, so that prefix also avoids the ambiguity.
Delete Without Undo
rm project/docs/guide.md
rmdir project/testrmdir only removes empty directories. rm -r recursively deletes directory trees and typically does not send them to the trash. Do not observe the protection mechanism by running rm -rf /; the actual outcome depends on implementation, permissions, and mount environment.
Before deleting a directory, follow a four-step verification process:
target="$workdir/project/docs-backup"
pwd
ls -ld -- "$target"
find "$target" -print
rm -r -- "$target"rm -i prompts can reduce accidental deletions, but they are not a safety guarantee. Scripts, aliases, and different implementations may behave differently.
Final cleanup:
cd
ls -ld -- "$workdir"
rm -r -- "$workdir"