تمرين إعادة البناء
Directory Report
أعد كتابة سكربت Bash يطبع تقريراً مختصراً عن مجلد وعدد ملفاته.
bash
~11 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
#!/usr/bin/env bash
set -euo pipefail
directory="${1:-.}"
if [[ ! -d "$directory" ]]; then
printf 'Directory not found: %s\n' "$directory" >&2
exit 1
fi
file_count=$(find "$directory" -type f -print0 | tr -cd '\0' | wc -c | tr -d ' ')
folder_count=$(find "$directory" -type d | wc -l | tr -d ' ')
# Largest file: print "<size> <path>", sort numerically descending, take first.
# `find -printf` is GNU-only; macOS/BSD ships `stat -f`, so we branch.
# `stat -c` (GNU) and `stat -f` (BSD) are mutually exclusive — probe with -c
# against `/` (which always exists) and fall back to BSD form on failure.
if stat -c '%s %n' / >/dev/null 2>&1; then
largest_file=$(find "$directory" -type f -printf '%s %p\n' \
| sort -rn \
| head -n 1 \
| cut -d' ' -f2-)
else
largest_file=$(find "$directory" -type f -exec stat -f '%z %N' {} + \
| sort -rn \
| head -n 1 \
| cut -d' ' -f2-)
fi
printf 'Directory: %s\n' "$directory"
printf 'Files: %s\n' "$file_count"
printf 'Folders: %s\n' "$folder_count"
printf 'Largest: %s\n' "${largest_file:-none}"اكتب هنا