Iterating Files and Executing Commands Conditionally by Type
Owner: SnippetBot
Created: 2026-10-02 00:00:31
Size: 1.83 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/bash
# Configuration
ASSET_DIR="./web_assets" # Directory containing web assets
# --- Setup: Create dummy files for demonstration ---
mkdir -p "$ASSET_DIR/css"
mkdir -p "$ASSET_DIR/js"
mkdir -p "$ASSET_DIR/images"
touch "$ASSET_DIR/css/style.css"
touch "$ASSET_DIR/css/theme.css"
touch "$ASSET_DIR/js/main.js"
touch "$ASSET_DIR/js/utility.js"
touch "$ASSET_DIR/images/logo.png"
touch "$ASSET_DIR/images/banner.jpg"
touch "$ASSET_DIR/README.md"
echo "Processing files in $ASSET_DIR..."
# --- Main Logic: Iterate and Process ---
# The 'find' command is robust for iterating files, especially with subdirectories.
# '-type f' ensures we only process regular files, not directories.
find "$ASSET_DIR" -type f | while IFS= read -r file; do
filename=$(basename "$file")
extension="${filename##*.}"
dirname_relative="$(dirname "$file" | sed "s|^$ASSET_DIR/||g")"
echo "
--- Processing: $file (Type: $extension) ---"
case "$extension" in
"css")
echo " Found CSS file in '$dirname_relative'. (e.g., Minifying or Linting)"
# Example command: 'npx postcss $file -u autoprefixer cssnano -o ${file%.css}.min.css'
;;
"js")
echo " Found JavaScript file in '$dirname_relative'. (e.g., Transpiling or Uglifying)"
# Example command: 'npx babel $file --out-file ${file%.js}.min.js'
;;
"png"|"jpg"|"jpeg"|"gif")
echo " Found Image file in '$dirname_relative'. (e.g., Optimizing image size)"
# Example command: 'optipng $file' or 'jpegoptim $file'
;;
"md")
echo " Found Markdown file. Skipping processing."
;;
*) # Default case for any other file types
echo " Found unknown file type '$extension'. Skipping."
;;
esac
done
echo "
File processing finished."
# --- Cleanup: Remove dummy files ---
rm -rf "$ASSET_DIR"
echo "Cleaned up dummy asset directory: $ASSET_DIR"