Welcome back to Automating Tasks with zsh Scripts! Two units in, our tidy.zsh has a tidy control panel of variables at the top and quoted expansions throughout. It is still a script that hopes for the best, though: it creates archive blindly and copies My Notes/report.txt as if that path were always present, always a regular file, and always full of text.
Four ordinary situations can occur:
The archive directory already exists from a previous run.
The report exists as a regular file but is completely empty.
A path named report.txt exists but is something other than a regular file, such as a directory.
The report is not there at all.
In this unit, we add decisions with if, elif, and else, driven by the file tests -d, -f, -s, and -e. The reward is a script that says which situation it found instead of failing or, worse, printing a cheerful message about work it never did. By the end, one script will produce six clearly different runs: creation and reuse of the archive, plus filled, empty, non-regular, and missing report cases.
Preparing the Sandbox
As always, we start with a small workspace built from commands you already know from earlier courses.
The starting state is a filled report.txt inside a folder with a space in its name, with no archive directory yet.
Later, we will change the report's state so every branch gets its turn.
The Shape of an if Statement in zsh
Before we test any files, let us look at the skeleton on its own.
Shell
if [ … ]; then …else …fi
Each token has a job:
[ is not punctuation; it is a real command that evaluates the condition inside it and reports success or failure through its exit status. Because it is a command, the spaces after [ and before ] are required: [-d "$dir"] would send zsh looking for a command named [-d.
then must be separated from the condition, either by a ; on the same line or by starting a new line.
fi—that is, if spelled backward—closes the block.
We can insert one or more elif [ … ]; then branches between the first branch and else. Conditions are checked from top to bottom, and only the first true branch runs; else catches everything that matched nothing.
An if condition can also be a list of commands joined with &&:
Shell
if [ -f "$report" ] && [ -s "$report" ]; then echo "the regular file has contents"fi
The second test runs only when the first test succeeds. Here, the script asks two questions before copying: "Is this a regular file?" and "Does it contain data?"
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Four File Tests: -d, -f, -s, and -e
Branch One: Create the Destination Only When Needed
Here is the first decision in the script, using the archive_dir variable assigned at the top.
if [ -d "$archive_dir" ]; then echo "reusing $archive_dir"else mkdir -p "$archive_dir" echo "created $archive_dir"fi
If archive already exists as a directory, we say so and move on. Otherwise, we create it and then report the creation. A fair question: mkdir -p "$archive_dir" on its own never complains about an existing directory, so why bother testing?
The answer is not safety but visibility. mkdir -p is silent, and silence hides useful information: Was this a fresh setup or the fifth run of the day? Branching lets the script announce which path it took, and a script that narrates its own decisions is one we can debug from its output alone.
Branch Two: Filled, Empty, Non-Regular, or Missing
Assembling tidy.zsh
Running Every Branch
Now we drive the script through each situation in turn. The first two runs differ only in what already exists on disk.
./tidy.zsh
On this first run, -d "archive" fails, so the else branch creates the directory. The report is a regular file with content, so the combined -f and -s test succeeds.
created archivearchived report.txt into archive
Run it again without touching anything:
./tidy.zsh
Nothing about the report has changed, but -d now succeeds, and the message flips from created to reusing.
reusing archivearchived report.txt into archive
Emptying the Report
Next, truncate the report to zero bytes without removing it.
printf '' > "My Notes/report.txt"./tidy.zsh
The path still passes -f, but it fails -s, so the first elif speaks. No copy occurs.
reusing archivereport.txt exists but is empty
The archive still contains the earlier copy because the empty run did not call cp.
Replacing the Report with a Directory
Now remove the regular file and create a directory with the same name.
rm "My Notes/report.txt"mkdir -p "My Notes/report.txt"./tidy.zsh
The path exists, so -e succeeds. However, -f fails because the path is a directory. The script reports the situation instead of trying to copy the directory.
reusing archivereport.txt exists but is not a regular file
This is the case that exposes the difference between -s and -f. A directory may have a nonzero size, so -s alone is not enough to decide whether cp should receive the path.
Deleting the Report
Now remove the directory entirely.
rm -R "My Notes/report.txt"./tidy.zsh
All three existence-related tests fail. The final else correctly reports that the report is missing.
reusing archivereport.txt is missing from My Notes
The difference between this output and the previous one is meaningful: one path exists but is the wrong kind of object, while the other path is absent.
Back to the Successful Path
Finally, restore the report with content and confirm what actually landed in the archive.
printf 'draft notes\n' > "My Notes/report.txt"./tidy.zshls archive
Recreating the regular file with content makes both -f and -s succeed again, so the script returns to copying.
reusing archivearchived report.txt into archivedaily-report.txt
The closing ls archive is the evidence that matters: exactly one file, daily-report.txt, written by the first successful run and overwritten by the final one. The empty and non-regular runs left the archive untouched rather than copying something unusable over a good report.
The condition inside the brackets is where the interesting part lives.
Shell
[ -d "archive" ] # true if archive exists and is a directory[ -f "My Notes/report.txt" ] # true if the path exists and is a regular file[ -s "My Notes/report.txt" ] # true if the path has a size above zero[ -e "My Notes/report.txt" ] # true if anything exists at that path
The important correction is that -s tests size, not file type. A directory can have a nonzero size, so this test may succeed for a directory named report.txt even though the directory is not a regular file and should not be passed to an ordinary cp.
Therefore, the useful question "is there a regular file here with something in it?" requires two tests:
Shell
[ -f "$report" ] && [ -s "$report" ]
The relationship among the tests is:
-e is the broadest test: something exists at the path.
-f identifies regular files within the set of existing paths.
-s identifies paths with nonzero size. Some regular files pass it, but non-regular paths such as directories can also pass it.
A regular file can pass -f while failing -s when it is empty.
A missing path fails all four tests, and no error is printed; the test simply reports failure.
The following table summarizes the cases:
Path situation
-e
-f
-s
Filled regular file
true
true
true
Empty regular file
true
true
false
Non-regular path with nonzero size, such as a directory
true
false
possibly true
Missing path
false
false
false
Updated relationship among the zsh file tests
-e: something exists├── -f: regular file│ ├── -s: regular file with nonzero size│ └── regular file with zero size└── exists, but is not a regular file └── some such paths may also pass -s
Notice the double quotes around every tested path. That is the Unit 2 rule again: a spaced name stays one argument, and an empty value fails visibly instead of vanishing.
Shell
if [ -d "$archive_dir" ]; then echo "reusing $archive_dir"else mkdir -p "$archive_dir" echo "created $archive_dir"fi
Now, the four-way decision about the report.
Shell
report="$source_dir/report.txt"if [ -f "$report" ] && [ -s "$report" ]; then cp "$report" "$archive_dir/$label-report.txt" echo "archived report.txt into $archive_dir"elif [ -f "$report" ]; then echo "report.txt exists but is empty"elif [ -e "$report" ]; then echo "report.txt exists but is not a regular file"else echo "report.txt is missing from $source_dir"fi
There are four distinct outcomes, and the ordering makes each one reachable:
The first branch is the strictest: the path must be a regular file and have nonzero size. Only then does the script call cp.
The first elif is reached when the path is a regular file but the size test fails. That is the empty-file case.
The second elif catches a path that exists but is not a regular file, such as a directory named report.txt. The -f guard is what keeps that directory out of the copy branch.
The final else is reached only after -f, -s, and -e have all failed, so the path is genuinely absent.
Swapping these conditions would cause problems. If -s were used alone in the first branch, a nonempty directory could be sent to cp. If -e came before -f, an existing regular file would be classified too broadly and never reach the filled or empty branches.
Put the script together in two stages. Open tidy.zsh in your editor and start with the shebang, the assignments, and the first decision.
The layout already tells part of the story: every assignment comes first, so the values are easy to find and change, and report is built from source_dir instead of repeating My Notes by hand.
Part 2: The Report Branch
Below that block, leave a blank line and add the four-way decision.
Shell
if [ -f "$report" ] && [ -s "$report" ]; then cp "$report" "$archive_dir/$label-report.txt" echo "archived report.txt into $archive_dir"elif [ -f "$report" ]; then echo "report.txt exists but is empty"elif [ -e "$report" ]; then echo "report.txt exists but is not a regular file"else echo "report.txt is missing from $source_dir"fi
A blank line separates the two decisions, and each branch body is indented by two spaces, so the four outcomes are readable at a glance.
Save the file and make it executable as in earlier units.
Shell
chmod u+x tidy.zsh
Shell
./tidy.zsh
text
created archivearchived report.txt into archive
Shell
./tidy.zsh
text
reusing archivearchived report.txt into archive
Shell
printf '' > "My Notes/report.txt"./tidy.zsh
text
reusing archivereport.txt exists but is empty
Shell
rm "My Notes/report.txt"mkdir -p "My Notes/report.txt"./tidy.zsh
text
reusing archivereport.txt exists but is not a regular file
Shell
rm -R "My Notes/report.txt"./tidy.zsh
text
reusing archivereport.txt is missing from My Notes
Shell
printf 'draft notes\n' > "My Notes/report.txt"./tidy.zshls archive
text
reusing archivearchived report.txt into archivedaily-report.txt
Our script now inspects the world before changing it. The rules worth carrying forward are:
[ … ] is a command: keep the spaces, separate the condition from then with ; or a newline, and close the block with fi.
-d asks, "Is this a directory?"; -f asks, "Is this a regular file?"; -s asks, "Does this path have nonzero size?"; and -e asks, "Does anything exist here?"
Combine -f with -s before copying, and order the branches from most specific to least specific.
Use -e to distinguish an existing non-regular path from a genuinely missing path.
Double-quote every tested path, exactly as with any other expansion.
Print one message per branch, so the output explains itself.
One limitation remains: choosing a different source or label still means editing an assignment inside the file. In Unit 4, those values will arrive from the command line through $1 and $2, and if will take on a new job: refusing to run when the arguments are wrong. Before that, the practices are ready for you: go make each branch fire, and watch your script tell you exactly which situation it found.
text
-e: something exists├── -f: regular file│ ├── -s: regular file with nonzero size│ └── regular file with zero size└── exists, but is not a regular file └── some such paths may also pass -s