You are writing a portable Bourne-compatible shell script that must compress any log file in /var/log that exceeds 100 MiB (104 857 600 bytes). The loop must:
Confirm that each entry is a regular file before acting.
Compare the file's size against the byte threshold using POSIX-defined numeric operators.
Which snippet meets both requirements while remaining compatible with a standard /bin/sh on Linux?
for f in /var/log/*; do
test -f "$f" && test $(stat -c%s "$f") > 104857600 && gzip "$f"
done
for f in /var/log/*; do
[ -f "$f" ] && [ $(stat -c%s "$f") -gt 104857600 ] && gzip "$f"
done
for f in /var/log/*; do
[[ -d "$f" ]] && [[ $(du -m "$f" | cut -f1) -gt 100 ]] && gzip "$f"
done
for f in /var/log/*; do
if (( $(stat -c%s "$f") > 104857600 )); then gzip "$f"; fi
done
The first snippet chains two separate POSIX‐compliant tests with the && operator:
[ -f "$f" ] verifies that the pathname refers to a regular file.
$(stat -c%s "$f") -gt 104857600 obtains the size in bytes with stat and performs a numeric greater-than comparison using -gt.
If both tests succeed, gzip runs; otherwise the next file is examined. All commands (for, test/[ ], stat, gzip) are available on a typical Linux system and require no Bash-specific extensions.
The second snippet checks for directories, not regular files, and therefore skips every log file. The third snippet attempts to use the redirection operator > inside test, which redirects output instead of performing a numeric comparison. The fourth snippet relies on the arithmetic compound command (( )), which is a Bash extension and not guaranteed in /bin/sh.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
Why is "/bin/sh" compatibility significant for shell scripts?
Open an interactive chat with Bash
What does `[ -f "$f" ]` check in the script?
Open an interactive chat with Bash
Why is `stat -c%s` used to get the file size?
Open an interactive chat with Bash
CompTIA Linux+ XK0-006 (V8)
Automation, Orchestration, and Scripting
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
IT & Cybersecurity Package Join Premium for Full Access