02 / FILES AND STREAMS · LESSON 05

Creating and managing files

Create a report directory and copy, rename and remove files safely.

13 min · learn at your pace

Small file operations compose

mkdir -p creates a directory and any missing parents. cp copies a file, mv renames or moves it, and rm removes it. Each command takes separate path arguments; quote each one. Start paths with ./ when a relative filename might begin with a dash.

A copy preserves evidence; editing the original does not. This course treats supplied data as evidence unless a task explicitly says otherwise. Create reports in a separate directory and use a deliberate output name. Do not parse ls output to obtain filenames: spacing and formatting are for people, not a reliable data format.

Repetition should be predictable

A useful script often runs again after a correction. Creating a directory should still work when it already exists. Replacing a report should not append an accidental second copy. Remove only the temporary file you created; never use broad cleanup patterns against a directory you have not checked.

The browser saves regular files and directories under /home/user. Permissions, symbolic links and special files are not included in saved snapshots. Run uses Bash directly, so these lessons do not require executable permission on main.sh.

Try an example.sh
mkdir -p './reports'
cp './source note.txt' './reports/note.txt'
YOUR TURN

Put it into practice.

Create `reports/archive.txt` containing an unchanged copy of `source note.txt`. First copy it to `reports/staging.txt`, then rename it. Create and remove `reports/scratch.txt`. Leave the source unchanged and no staging/scratch files. Repeated runs must succeed.

See an explained solution
One way to solve it.sh
mkdir -p './reports' || exit 1
cp './source note.txt' './reports/staging.txt' || exit 1
mv './reports/staging.txt' './reports/archive.txt' || exit 1
printf 'temporary\n' > './reports/scratch.txt'
rm './reports/scratch.txt'

Each destructive operation targets a specific report path. The source remains evidence and the final copy is replaced on each run.