File and Directory Operations

Performs file and directory operations including creation, copying, moving, permission management, and safe file handling with proper error checking.

BashConfig Management

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

work_dir="/tmp/bash-demo-$$"
mkdir -p "$work_dir/subdir"
echo "Created: $work_dir"

# Create files with content
cat > "$work_dir/config.txt" << 'EOF'
server_host=localhost
server_port=8080
debug=true
EOF

# Append to file
echo "log_level=info" >> "$work_dir/config.txt"

# Read and parse config
while IFS="=" read -r key value; do
    [[ "$key" =~ ^# ]] && continue
    [[ -z "$key" ]] && continue
    echo "Config: $key = $value"
done < "$work_dir/config.txt"

# File metadata
file="$work_dir/config.txt"
echo "Size: $(stat -c%s "$file") bytes"
echo "Permissions: $(stat -c%A "$file")"
echo "Owner: $(stat -c%U "$file")"

# Change permissions
chmod 644 "$file"
chmod 755 "$work_dir/subdir"

# Copy and move
cp "$file" "$work_dir/subdir/config-copy.txt"
mv "$work_dir/subdir/config-copy.txt" "$work_dir/config-backup.txt"

# Check file integrity
if cmp -s "$file" "$work_dir/config-backup.txt"; then
    echo "Files are identical"
fi

# Safe cleanup with trap
cleanup() {
    echo "Cleaning up $work_dir..."
    rm -rf "$work_dir"
}
trap cleanup EXIT

echo "Script complete, cleanup will run on exit"