Skip to main content

Conditional Statements

5.1 If statements

Nazariya

Shartli operatorlar dastur oqimini boshqarish uchun ishlatiladi. Ular shartlarga qarab turli kod bloklarini bajarish imkonini beradi.

If statement turlari:

  • if-then-fi - oddiy shart
  • if-then-else-fi - ikki holatli shart
  • if-elif-else-fi - ko'p holatli shart
  • Nested if - ichma-ich shartlar

Sintaksis:

if [ shart ]; then
# kod
elif [ boshqa_shart ]; then
# boshqa kod
else
# default kod
fi

Amaliyot

#!/bin/bash

# =====================================
# BASIC IF STATEMENTS
# =====================================

basic_if_demo() {
echo "=== Asosiy If Statements ==="

# Simple if statement
local age=25
echo "Yosh: $age"

if [ $age -ge 18 ]; then
echo "✅ Siz kattasiz"
fi
echo

# If-else statement
local temperature=15
echo "Harorat: ${temperature}°C"

if [ $temperature -gt 20 ]; then
echo "🌞 Issiq kun"
else
echo "🧥 Sovuq kun"
fi
echo

# Multiple conditions with elif
local score=85
echo "Ball: $score"

if [ $score -ge 90 ]; then
echo "🥇 A'lo bahosi"
elif [ $score -ge 80 ]; then
echo "🥈 Yaxshi bahosi"
elif [ $score -ge 70 ]; then
echo "🥉 Qoniqarli bahosi"
elif [ $score -ge 60 ]; then
echo "📝 O'rtacha bahosi"
else
echo "❌ Yomon bahosi"
fi
echo
}

# =====================================
# FILE AND DIRECTORY TESTS
# =====================================

file_tests_demo() {
echo "=== File va Directory Testlari ==="

# Create test files and directories
mkdir -p test_dir
touch test_file.txt
echo "test content" > test_file.txt
chmod 755 test_file.txt

local file_path="test_file.txt"
local dir_path="test_dir"
local missing_file="missing.txt"

echo "Test ob'ektlari: $file_path, $dir_path"
echo

# File existence tests
echo "Mavjudlik testlari:"
if [ -e "$file_path" ]; then
echo "✅ $file_path mavjud"
else
echo "❌ $file_path mavjud emas"
fi

if [ -f "$file_path" ]; then
echo "✅ $file_path oddiy fayl"
else
echo "❌ $file_path oddiy fayl emas"
fi

if [ -d "$dir_path" ]; then
echo "✅ $dir_path katalog"
else
echo "❌ $dir_path katalog emas"
fi

if [ -e "$missing_file" ]; then
echo "✅ $missing_file mavjud"
else
echo "❌ $missing_file mavjud emas"
fi
echo

# Permission tests
echo "Ruxsat testlari:"
if [ -r "$file_path" ]; then
echo "✅ $file_path o'qilishi mumkin"
else
echo "❌ $file_path o'qilmaydi"
fi

if [ -w "$file_path" ]; then
echo "✅ $file_path ga yozish mumkin"
else
echo "❌ $file_path ga yozib bo'lmaydi"
fi

if [ -x "$file_path" ]; then
echo "✅ $file_path bajarilishi mumkin"
else
echo "❌ $file_path bajarilmaydi"
fi
echo

# File size and age tests
echo "Hajm va vaqt testlari:"
if [ -s "$file_path" ]; then
echo "✅ $file_path bo'sh emas"
echo " Hajm: $(wc -c < "$file_path") bayt"
else
echo "❌ $file_path bo'sh"
fi

# Compare file modification times
if [ "$file_path" -nt "$dir_path" ]; then
echo "✅ $file_path $dir_path dan yangi"
else
echo "❌ $file_path $dir_path dan eski yoki bir xil"
fi
echo

# Cleanup
rm -f test_file.txt
rmdir test_dir
}

# =====================================
# STRING TESTS AND VALIDATION
# =====================================

string_tests_demo() {
echo "=== String Testlari va Validatsiya ==="

# Email validation
validate_email() {
local email="$1"
echo "Email tekshiruvi: '$email'"

if [ -z "$email" ]; then
echo "❌ Email bo'sh"
return 1
elif [[ ! "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "❌ Noto'g'ri email format"
return 1
else
echo "✅ To'g'ri email"
return 0
fi
}

# Phone validation (Uzbekistan format)
validate_phone() {
local phone="$1"
echo "Telefon tekshiruvi: '$phone'"

# Clean phone number
phone="${phone// /}" # Remove spaces
phone="${phone//-/}" # Remove dashes
phone="${phone//(/}" # Remove (
phone="${phone//)/}" # Remove )

if [ -z "$phone" ]; then
echo "❌ Telefon raqami bo'sh"
return 1
elif [[ ${#phone} -lt 9 ]]; then
echo "❌ Telefon raqami juda qisqa"
return 1
elif [[ ! "$phone" =~ ^(\+998|998|8)?[0-9]{9}$ ]]; then
echo "❌ Noto'g'ri telefon format"
return 1
else
echo "✅ To'g'ri telefon raqami"
return 0
fi
}

# Password strength validation
validate_password() {
local password="$1"
local errors=0

echo "Parol kuchi tekshiruvi:"

if [ ${#password} -lt 8 ]; then
echo "❌ Juda qisqa (kamida 8 belgi)"
((errors++))
else
echo "✅ Uzunlik yetarli (${#password} belgi)"
fi

if [[ ! "$password" =~ [A-Z] ]]; then
echo "❌ Katta harf yo'q"
((errors++))
else
echo "✅ Katta harf mavjud"
fi

if [[ ! "$password" =~ [a-z] ]]; then
echo "❌ Kichik harf yo'q"
((errors++))
else
echo "✅ Kichik harf mavjud"
fi

if [[ ! "$password" =~ [0-9] ]]; then
echo "❌ Raqam yo'q"
((errors++))
else
echo "✅ Raqam mavjud"
fi

if [[ ! "$password" =~ [^a-zA-Z0-9] ]]; then
echo "❌ Maxsus belgi yo'q"
((errors++))
else
echo "✅ Maxsus belgi mavjud"
fi

if [ $errors -eq 0 ]; then
echo "🔒 Kuchli parol!"
return 0
else
echo "⚠️ Zaif parol ($errors ta kamchilik)"
return 1
fi
}

# Test validation functions
echo "Validatsiya testlari:"
echo

validate_email "user@example.com"
echo
validate_email "invalid-email"
echo

validate_phone "+998901234567"
echo
validate_phone "90 123 45 67"
echo
validate_phone "invalid"
echo

validate_password "MyStr0ng!Pass"
echo
validate_password "weak"
echo
}

# =====================================
# NESTED IF STATEMENTS
# =====================================

nested_if_demo() {
echo "=== Ichma-ich If Statements ==="

# User access control system
user_access_control() {
local username="$1"
local password="$2"
local resource="$3"

echo "Kirish nazorati: user='$username', resource='$resource'"

# First level: Authentication
if [ "$username" == "admin" ] && [ "$password" == "admin123" ]; then
echo "✅ Admin muvaffaqiyatli kiri"

# Admin has access to everything
echo "✅ Admin barcha resurslarga kirish huquqiga ega"
return 0

elif [ "$username" == "user1" ] && [ "$password" == "pass123" ]; then
echo "✅ User1 muvaffaqiyatli kirdi"

# Second level: Authorization for user1
if [ "$resource" == "read" ]; then
echo "✅ User1 o'qish huquqiga ega"
return 0
elif [ "$resource" == "write" ]; then
echo "❌ User1 yozish huquqiga ega emas"
return 1
else
echo "❌ User1 '$resource' huquqiga ega emas"
return 1
fi

elif [ "$username" == "guest" ]; then
echo "✅ Guest foydalanuvchi"

# Guest doesn't need password but has limited access
if [ "$resource" == "read" ]; then
echo "✅ Guest o'qish huquqiga ega"
return 0
else
echo "❌ Guest faqat o'qish huquqiga ega"
return 1
fi

else
echo "❌ Noto'g'ri username yoki parol"
return 1
fi
}

# Grade calculation with nested conditions
calculate_grade() {
local math_score="$1"
local english_score="$2"
local physics_score="$3"

echo "Baholar: Matematika=$math_score, Ingliz tili=$english_score, Fizika=$physics_score"

# First check if all scores are valid
if [ $math_score -ge 0 ] && [ $math_score -le 100 ] &&
[ $english_score -ge 0 ] && [ $english_score -le 100 ] &&
[ $physics_score -ge 0 ] && [ $physics_score -le 100 ]; then

echo "✅ Barcha baholar to'g'ri diapazonida"

local average=$(( (math_score + english_score + physics_score) / 3 ))
echo "O'rtacha ball: $average"

# Nested conditions for final grade
if [ $average -ge 90 ]; then
echo "🥇 A'lo (Excellent)"

# Check if student excels in all subjects
if [ $math_score -ge 95 ] && [ $english_score -ge 95 ] && [ $physics_score -ge 95 ]; then
echo "🌟 Barcha fanlar bo'yicha a'lo!"
fi

elif [ $average -ge 80 ]; then
echo "🥈 Yaxshi (Good)"

# Check weak subjects
if [ $math_score -lt 80 ] || [ $english_score -lt 80 ] || [ $physics_score -lt 80 ]; then
echo "⚠️ Ba'zi fanlarni yaxshilash kerak"

if [ $math_score -lt 80 ]; then
echo " - Matematikani yaxshilash kerak ($math_score)"
fi
if [ $english_score -lt 80 ]; then
echo " - Ingliz tilini yaxshilash kerak ($english_score)"
fi
if [ $physics_score -lt 80 ]; then
echo " - Fizikani yaxshilash kerak ($physics_score)"
fi
fi

elif [ $average -ge 70 ]; then
echo "📝 Qoniqarli (Satisfactory)"
echo "💡 Ko'proq harakat qiling!"

else
echo "❌ Yomon (Poor)"
echo "⚠️ Jiddiy o'qish kerak!"

# Check which subjects need most attention
local min_score=$math_score
local weak_subject="Matematika"

if [ $english_score -lt $min_score ]; then
min_score=$english_score
weak_subject="Ingliz tili"
fi

if [ $physics_score -lt $min_score ]; then
min_score=$physics_score
weak_subject="Fizika"
fi

echo "Eng zaif fan: $weak_subject ($min_score ball)"
fi

else
echo "❌ Noto'g'ri ball kiritilgan!"
echo "Baholar 0-100 oralig'ida bo'lishi kerak"
return 1
fi
}

# Test nested functions
echo "Kirish nazorati testlari:"
user_access_control "admin" "admin123" "delete"
echo
user_access_control "user1" "pass123" "read"
echo
user_access_control "user1" "pass123" "write"
echo
user_access_control "guest" "" "read"
echo

echo "Baho hisoblagich testlari:"
calculate_grade 95 98 92
echo
calculate_grade 85 78 82
echo
calculate_grade 65 70 68
echo
calculate_grade 45 55 50
echo
}

# =====================================
# ADVANCED CONDITIONS
# =====================================

advanced_conditions_demo() {
echo "=== Murakkab Shartlar ==="

# System health check
system_health_check() {
echo "Tizim sog'ligi tekshiruvi:"

# Get system metrics
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | sed 's/%us,//')
local memory_usage=$(free | awk '/^Mem:/ {printf "%.1f", $3/$2 * 100}')
local disk_usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
local load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')

echo "CPU ishlatilishi: ${cpu_usage:-0}%"
echo "RAM ishlatilishi: ${memory_usage:-0}%"
echo "Disk ishlatilishi: ${disk_usage:-0}%"
echo "Load average: ${load_avg:-0}"
echo

local health_score=100
local warnings=()
local critical_issues=()

# CPU check
if (( $(echo "${cpu_usage:-0} > 90" | bc -l) )); then
critical_issues+=("CPU juda yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 30))
elif (( $(echo "${cpu_usage:-0} > 70" | bc -l) )); then
warnings+=("CPU yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 15))
fi

# Memory check
if (( $(echo "${memory_usage:-0} > 90" | bc -l) )); then
critical_issues+=("RAM juda yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 25))
elif (( $(echo "${memory_usage:-0} > 80" | bc -l) )); then
warnings+=("RAM yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 10))
fi

# Disk check
if [ ${disk_usage:-0} -gt 95 ]; then
critical_issues+=("Disk juda to'la (${disk_usage}%)")
health_score=$((health_score - 35))
elif [ ${disk_usage:-0} -gt 85 ]; then
warnings+=("Disk to'la bo'lib bormoqda (${disk_usage}%)")
health_score=$((health_score - 20))
fi

# Load average check (assuming 4 CPU cores)
if (( $(echo "${load_avg:-0} > 8" | bc -l) )); then
critical_issues+=("Tizim juda yuklanган (load: ${load_avg})")
health_score=$((health_score - 20))
elif (( $(echo "${load_avg:-0} > 4" | bc -l) )); then
warnings+=("Tizim yuklanған (load: ${load_avg})")
health_score=$((health_score - 10))
fi

# Report health status
echo "=== SOGLIQ HISOBOTI ==="

if [ ${#critical_issues[@]} -gt 0 ]; then
echo "🚨 KRITIK MUAMMOLAR:"
for issue in "${critical_issues[@]}"; do
echo " ❌ $issue"
done
echo
fi

if [ ${#warnings[@]} -gt 0 ]; then
echo "⚠️ OGOHLANTIRISHLAR:"
for warning in "${warnings[@]}"; do
echo " ⚠️ $warning"
done
echo
fi

echo "Sog'liq darajasi: $health_score/100"

if [ $health_score -ge 90 ]; then
echo "💚 Tizim sog'lom"
elif [ $health_score -ge 70 ]; then
echo "💛 Tizim qoniqarli holatda"
elif [ $health_score -ge 50 ]; then
echo "🧡 Tizim muammoli"
else
echo "❤️ Tizim kritik holatda"
fi
echo
}

# Backup strategy selector
backup_strategy() {
local file_count="$1"
local total_size="$2" # in MB
local available_space="$3" # in MB
local is_weekend="$4" # true/false

echo "Backup strategiyasi tanlash:"
echo "Fayllar soni: $file_count"
echo "Umumiy hajm: ${total_size}MB"
echo "Mavjud joy: ${available_space}MB"
echo "Dam olish kunemi: $is_weekend"
echo

local strategy=""
local compression_level=""
local schedule=""

# Choose strategy based on conditions
if [ $total_size -gt $available_space ]; then
echo "❌ Yetarli joy yo'q - backup imkonsiz"
return 1
elif [ $file_count -gt 100000 ] || [ $total_size -gt 10000 ]; then
# Large backup
strategy="incremental"
compression_level="high"

if [ "$is_weekend" == "true" ]; then
schedule="full_backup"
echo "📦 Yirik backup - to'liq zaxira nusxa (dam olish kuni)"
else
schedule="incremental_only"
echo "📦 Yirik backup - faqat o'zgarishlar"
fi

elif [ $file_count -gt 10000 ] || [ $total_size -gt 1000 ]; then
# Medium backup
strategy="differential"
compression_level="medium"

if [ "$is_weekend" == "true" ]; then
schedule="differential"
echo "📋 O'rtacha backup - differensial"
else
schedule="quick"
echo "📋 O'rtacha backup - tezkor"
fi

else
# Small backup
strategy="full"
compression_level="low"
schedule="immediate"
echo "📄 Kichik backup - to'liq va tezkor"
fi

# Calculate estimated time
local estimated_minutes
if [ "$compression_level" == "high" ]; then
estimated_minutes=$((total_size / 50)) # ~50MB per minute with high compression
elif [ "$compression_level" == "medium" ]; then
estimated_minutes=$((total_size / 100)) # ~100MB per minute with medium compression
else
estimated_minutes=$((total_size / 200)) # ~200MB per minute with low compression
fi

echo
echo "Tavsiya etilgan strategiya:"
echo " Turi: $strategy"
echo " Siqish darajasi: $compression_level"
echo " Rejalashtirish: $schedule"
echo " Taxminiy vaqt: ${estimated_minutes} daqiqa"

# Additional recommendations
if [ $available_space -lt $((total_size * 2)) ]; then
echo "⚠️ Tavsiya: Ko'proq bo'sh joy ajrating"
fi

if [ "$is_weekend" == "false" ] && [ $estimated_minutes -gt 60 ]; then
echo "⚠️ Tavsiya: Backup ni kechqurun yoki dam olish kuniga o'tkazing"
fi

return 0
}

# Test advanced conditions
echo "Tizim sog'ligi tekshiruvi:"
system_health_check

echo "Backup strategiya testlari:"
backup_strategy 50000 5000 20000 "true"
echo
backup_strategy 1000 500 2000 "false"
echo
backup_strategy 200000 15000 12000 "false"
echo
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_if_demo
file_tests_demo
string_tests_demo
nested_if_demo
advanced_conditions_demo
fi

5.2 Test conditions

Nazariya

Test shartlari bash da [ ], [[ ]], va test buyrug'i orqali amalga oshiriladi. Har birining o'z afzalliklari va ishlatilish joylari bor.

Test operatorlari turlari:

  • File tests - fayl va katalog holati
  • String tests - matn taqqoslashi
  • Numeric tests - raqamli taqqoslash
  • Logical tests - mantiqiy operatsiyalar

Sintaksis farqlari:

  • [ ] - POSIX standart, portable
  • [[ ]] - Bash extended, qo'shimcha imkoniyatlar
  • test - klasik Unix buyrug'i

Amaliyot

#!/bin/bash

# =====================================
# TEST COMMAND VARIATIONS
# =====================================

test_syntax_demo() {
echo "=== Test Buyrug'i Sintaksis Farqlari ==="

local num=42
local str="hello"
local file="test.txt"

echo "O'zgaruvchilar: num=$num, str='$str', file='$file'"
echo

# Create test file
echo "test content" > "$file"

echo "Turli test sintakslari:"

# Using test command
if test $num -eq 42; then
echo "✅ test buyrug'i: $num = 42"
fi

# Using [ ] (same as test)
if [ $num -eq 42 ]; then
echo "✅ [ ] sintaksi: $num = 42"
fi

# Using [[ ]] (bash extended)
if [[ $num -eq 42 ]]; then
echo "✅ [[ ]] sintaksi: $num = 42"
fi
echo

# String comparison differences
echo "String taqqoslash farqlari:"

# [ ] requires quotes for variables
if [ "$str" = "hello" ]; then
echo "✅ [ ] bilan string taqqoslash (qo'shtirnoq kerak)"
fi

# [[ ]] doesn't require quotes (but good practice to use them)
if [[ $str == "hello" ]]; then
echo "✅ [[ ]] bilan string taqqoslash"
fi

# [[ ]] supports pattern matching
if [[ $str == h* ]]; then
echo "✅ [[ ]] pattern matching: '$str' 'h' bilan boshlanadi"
fi

# [[ ]] supports regex
if [[ $str =~ ^h.* ]]; then
echo "✅ [[ ]] regex: '$str' regex ga mos keladi"
fi
echo

# Cleanup
rm -f "$file"
}

# =====================================
# COMPREHENSIVE FILE TESTS
# =====================================

comprehensive_file_tests() {
echo "=== To'liq File Testlari ==="

# Create test environment
mkdir -p test_env
cd test_env

# Create different types of files
echo "regular file content" > regular_file.txt
mkdir directory
touch empty_file
ln -s regular_file.txt symbolic_link
mkfifo named_pipe 2>/dev/null || echo "FIFO yaratib bo'lmadi"

# Make executable file
echo '#!/bin/bash\necho "executable"' > script.sh
chmod +x script.sh

# Create read-only file
echo "read only content" > readonly_file.txt
chmod 444 readonly_file.txt

local files=(
"regular_file.txt"
"directory"
"empty_file"
"symbolic_link"
"named_pipe"
"script.sh"
"readonly_file.txt"
"nonexistent_file"
)

echo "Test ob'ektlari yaratildi"
echo

# Test each file type
for item in "${files[@]}"; do
echo "Testing: $item"

if [ -e "$item" ]; then
echo " ✅ Mavjud (-e)"
else
echo " ❌ Mavjud emas (-e)"
continue
fi

if [ -f "$item" ]; then
echo " 📄 Oddiy fayl (-f)"
elif [ -d "$item" ]; then
echo " 📁 Katalog (-d)"
elif [ -L "$item" ]; then
echo " 🔗 Simbolik link (-L)"
elif [ -p "$item" ]; then
echo " 📡 Named pipe (-p)"
fi

if [ -r "$item" ]; then
echo " 👁️ O'qilishi mumkin (-r)"
else
echo " 🚫 O'qilmaydi (-r)"
fi

if [ -w "$item" ]; then
echo " ✏️ Yozilishi mumkin (-w)"
else
echo " 🔒 Yozilmaydi (-w)"
fi

if [ -x "$item" ]; then
echo " ⚡ Bajarilishi mumkin (-x)"
else
echo " ⏹️ Bajarilmaydi (-x)"
fi

if [ -s "$item" ]; then
echo " 📊 Bo'sh emas (-s), hajm: $(wc -c < "$item" 2>/dev/null || echo "?") bayt"
else
echo " 📭 Bo'sh (-s yo'q)"
fi

echo
done

# File comparison tests
echo "File taqqoslash testlari:"

# Create files for comparison
echo "content1" > file1.txt
sleep 1
echo "content2" > file2.txt
cp file1.txt file1_copy.txt

if [ file1.txt -nt file2.txt ]; then
echo "❌ file1.txt file2.txt dan yangi"
else
echo "✅ file1.txt file2.txt dan eski yoki bir xil"
fi

if [ file2.txt -nt file1.txt ]; then
echo "✅ file2.txt file1.txt dan yangi"
else
echo "❌ file2.txt file1.txt dan eski yoki bir xil"
fi

if [ file1.txt -ef file1_copy.txt ]; then
echo "✅ file1.txt va file1_copy.txt bir xil fayl"
else
echo "❌ file1.txt va file1_copy.txt har xil fayllar"
fi

# Cleanup
cd ..
rm -rf test_env
echo
}

# =====================================
# ADVANCED STRING TESTS
# =====================================

advanced_string_tests() {
echo "=== Murakkab String Testlari ==="

# Test data
local test_strings=(
""
" "
"hello"
"Hello World"
"user@example.com"
"+998901234567"
"192.168.1.1"
"2024-06-24"
"MyPassword123!"
" spaces "
)

echo "Test string lari:"
for i in "${!test_strings[@]}"; do
echo " [$i]: '${test_strings[i]}'"
done
echo

# String length and emptiness tests
echo "Uzunlik va bo'shliq testlari:"
for str in "${test_strings[@]}"; do
echo "String: '${str}'"

if [ -z "$str" ]; then
echo " ✅ Bo'sh string (-z)"
else
echo " ❌ Bo'sh emas (-z), uzunlik: ${#str}"
fi

if [ -n "$str" ]; then
echo " ✅ To'ldirilgan (-n)"
else
echo " ❌ Bo'sh (-n)"
fi

# Check for whitespace-only strings
if [[ "$str" =~ ^[[:space:]]*$ ]]; then
echo " ⚪ Faqat bo'shliqlar"
elif [[ "$str" =~ ^[[:space:]] ]] || [[ "$str" =~ [[:space:]]$ ]]; then
echo " ⚠️ Boshi yoki oxirida bo'shliq bor"
fi

echo
done

# Pattern matching tests
echo "Pattern matching testlari:"

local email="user@example.com"
local phone="+998901234567"
local ip="192.168.1.1"
local date="2024-06-24"
local password="MyPassword123!"

echo "Email validatsiya: '$email'"
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo " ✅ To'g'ri email format"
else
echo " ❌ Noto'g'ri email format"
fi

echo "Telefon validatsiya: '$phone'"
if [[ "$phone" =~ ^\+998[0-9]{9}$ ]]; then
echo " ✅ To'g'ri O'zbekiston telefon raqami"
else
echo " ❌ Noto'g'ri telefon format"
fi

echo "IP address validatsiya: '$ip'"
if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo " ✅ IP address formatiga mos"
# Additional validation for IP ranges
IFS='.' read -ra ADDR <<< "$ip"
local valid_ip=true
for octet in "${ADDR[@]}"; do
if [ "$octet" -gt 255 ]; then
valid_ip=false
break
fi
done

if [ "$valid_ip" = true ]; then
echo " ✅ To'g'ri IP address"
else
echo " ❌ IP address diapazondan tashqari"
fi
else
echo " ❌ Noto'g'ri IP format"
fi

echo "Sana validatsiya: '$date'"
if [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
echo " ✅ ISO sana formatiga mos (YYYY-MM-DD)"

# Extract year, month, day
local year="${date%-*-*}"
local month="${date#*-}"; month="${month%-*}"
local day="${date##*-}"

if [ "$year" -ge 1900 ] && [ "$year" -le 2100 ] &&
[ "$month" -ge 1 ] && [ "$month" -le 12 ] &&
[ "$day" -ge 1 ] && [ "$day" -le 31 ]; then
echo " ✅ To'g'ri sana qiymatlari"
else
echo " ❌ Noto'g'ri sana qiymatlari"
fi
else
echo " ❌ Noto'g'ri sana format"
fi

echo "Parol kuchi: '$password'"
local score=0

if [[ ${#password} -ge 8 ]]; then
echo " ✅ Uzunlik yetarli (${#password} >= 8)"
((score++))
else
echo " ❌ Juda qisqa (${#password} < 8)"
fi

if [[ "$password" =~ [A-Z] ]]; then
echo " ✅ Katta harf mavjud"
((score++))
else
echo " ❌ Katta harf yo'q"
fi

if [[ "$password" =~ [a-z] ]]; then
echo " ✅ Kichik harf mavjud"
((score++))
else
echo " ❌ Kichik harf yo'q"
fi

if [[ "$password" =~ [0-9] ]]; then
echo " ✅ Raqam mavjud"
((score++))
else
echo " ❌ Raqam yo'q"
fi

if [[ "$password" =~ [^a-zA-Z0-9] ]]; then
echo " ✅ Maxsus belgi mavjud"
((score++))
else
echo " ❌ Maxsus belgi yo'q"
fi

echo " 🏆 Parol darajasi: $score/5"
echo
}

# =====================================
# NUMERIC RANGE TESTS
# =====================================

numeric_range_tests() {
echo "=== Raqamli Diapazon Testlari ==="

# Age category function
categorize_age() {
local age="$1"
echo "Yosh kategoriyasi: $age"

if ! [[ "$age" =~ ^[0-9]+$ ]]; then
echo " ❌ Noto'g'ri raqam format"
return 1
fi

if [ "$age" -le 0 ]; then
echo " ❌ Noto'g'ri yosh"
elif [ "$age" -le 2 ]; then
echo " 👶 Chaqaloq (0-2 yosh)"
elif [ "$age" -le 5 ]; then
echo " 🧒 Kichik bola (3-5 yosh)"
elif [ "$age" -le 12 ]; then
echo " 👦 Bola (6-12 yosh)"
elif [ "$age" -le 17 ]; then
echo " 👦 O'smir (13-17 yosh)"
elif [ "$age" -le 25 ]; then
echo " 👨 Yosh katta (18-25 yosh)"
elif [ "$age" -le 40 ]; then
echo " 👨 Katta (26-40 yosh)"
elif [ "$age" -le 60 ]; then
echo " 👨 O'rta yosh (41-60 yosh)"
elif [ "$age" -le 80 ]; then
echo " 👴 Keksa (61-80 yosh)"
else
echo " 👴 Juda keksa (80+ yosh)"
fi
}

# Temperature category
categorize_temperature() {
local temp="$1"
echo "Harorat kategoriyasi: ${temp}°C"

if ! [[ "$temp" =~ ^-?[0-9]+$ ]]; then
echo " ❌ Noto'g'ri harorat format"
return 1
fi

if [ "$temp" -le -30 ]; then
echo " 🧊 Ekstremal sovuq"
elif [ "$temp" -le -10 ]; then
echo " ❄️ Juda sovuq"
elif [ "$temp" -le 0 ]; then
echo " 🌨️ Sovuq"
elif [ "$temp" -le 10 ]; then
echo " 🧥 Salqin"
elif [ "$temp" -le 20 ]; then
echo " 🌤️ Iliq"
elif [ "$temp" -le 30 ]; then
echo " ☀️ Issiq"
elif [ "$temp" -le 40 ]; then
echo " 🔥 Juda issiq"
else
echo " 🌋 Ekstremal issiq"
fi
}

# Grade to GPA conversion
grade_to_gpa() {
local grade="$1"
echo "Baho konvertatsiyasi: $grade"

if ! [[ "$grade" =~ ^[0-9]+$ ]] || [ "$grade" -lt 0 ] || [ "$grade" -gt 100 ]; then
echo " ❌ Baho 0-100 oralig'ida bo'lishi kerak"
return 1
fi

local gpa
local letter_grade

if [ "$grade" -ge 97 ]; then
gpa="4.0"
letter_grade="A+"
elif [ "$grade" -ge 93 ]; then
gpa="4.0"
letter_grade="A"
elif [ "$grade" -ge 90 ]; then
gpa="3.7"
letter_grade="A-"
elif [ "$grade" -ge 87 ]; then
gpa="3.3"
letter_grade="B+"
elif [ "$grade" -ge 83 ]; then
gpa="3.0"
letter_grade="B"
elif [ "$grade" -ge 80 ]; then
gpa="2.7"
letter_grade="B-"
elif [ "$grade" -ge 77 ]; then
gpa="2.3"
letter_grade="C+"
elif [ "$grade" -ge 73 ]; then
gpa="2.0"
letter_grade="C"
elif [ "$grade" -ge 70 ]; then
gpa="1.7"
letter_grade="C-"
elif [ "$grade" -ge 67 ]; then
gpa="1.3"
letter_grade="D+"
elif [ "$grade" -ge 65 ]; then
gpa="1.0"
letter_grade="D"
else
gpa="0.0"
letter_grade="F"
fi

echo " 📊 Letter grade: $letter_grade"
echo " 📈 GPA: $gpa"
}

# Test numeric categorizations
local test_ages=(5 13 18 25 45 70 85)
local test_temps=(-25 -5 5 15 25 35 45)
local test_grades=(65 75 85 90 95 100)

echo "Yosh kategoriya testlari:"
for age in "${test_ages[@]}"; do
categorize_age "$age"
echo
done

echo "Harorat kategoriya testlari:"
for temp in "${test_temps[@]}"; do
categorize_temperature "$temp"
echo
done

echo "Baho konvertatsiya testlari:"
for grade in "${test_grades[@]}"; do
grade_to_gpa "$grade"
echo
done
}

# =====================================
# ENVIRONMENT TESTS
# =====================================

environment_tests() {
echo "=== Environment Testlari ==="

# Check operating system
echo "Operatsion tizim tekshiruvi:"

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
echo "✅ Linux tizim"

# Check distribution
if [ -f /etc/os-release ]; then
source /etc/os-release
echo " 📋 Distributiv: $NAME $VERSION"
fi

# Check if running in container
if [ -f /.dockerenv ]; then
echo " 🐳 Docker container ichida"
elif [ -n "${container:-}" ]; then
echo " 📦 Container ichida: $container"
else
echo " 🖥️ Native Linux"
fi

elif [[ "$OSTYPE" == "darwin"* ]]; then
echo "✅ macOS tizim"
elif [[ "$OSTYPE" == "cygwin" ]]; then
echo "✅ Cygwin (Windows)"
elif [[ "$OSTYPE" == "msys" ]]; then
echo "✅ MSYS (Windows)"
else
echo "❓ Noma'lum tizim: $OSTYPE"
fi
echo

# Check shell capabilities
echo "Shell imkoniyatlari:"

if [ -n "$BASH_VERSION" ]; then
echo "✅ Bash shell, versiya: $BASH_VERSION"

# Check bash version for features
local bash_major="${BASH_VERSION%%.*}"
if [ "$bash_major" -ge 4 ]; then
echo " ✅ Zamonaviy Bash (4.0+) - barcha xususiyatlar mavjud"
else
echo " ⚠️ Eski Bash ($BASH_VERSION) - ba'zi xususiyatlar cheklangan"
fi
else
echo "❌ Bash emas"
fi

# Check important environment variables
echo
echo "Muhim environment o'zgaruvchilar:"

local important_vars=(
"USER:Foydalanuvchi nomi"
"HOME:Uy katalogi"
"PATH:Buyruqlar yo'li"
"SHELL:Default shell"
"TERM:Terminal turi"
"LANG:Til sozlamalari"
"PWD:Joriy katalog"
)

for var_info in "${important_vars[@]}"; do
IFS=':' read -r var_name description <<< "$var_info"
local var_value="${!var_name}"

if [ -n "$var_value" ]; then
echo " ✅ $var_name ($description): $var_value"
else
echo " ❌ $var_name ($description): mavjud emas"
fi
done
echo

# Check user permissions
echo "Foydalanuvchi ruxsatlari:"

if [ "$EUID" -eq 0 ]; then
echo " 🔴 Root foydalanuvchi - to'liq ruxsatlar"
else
echo " 👤 Oddiy foydalanuvchi (UID: $EUID)"

# Check sudo access
if sudo -n true 2>/dev/null; then
echo " ✅ Sudo ruxsati mavjud"
elif command -v sudo >/dev/null; then
echo " ⚠️ Sudo mavjud, lekin ruxsat yo'q"
else
echo " ❌ Sudo mavjud emas"
fi
fi

# Check groups
local user_groups=$(groups 2>/dev/null || echo "unknown")
echo " 👥 Guruhlar: $user_groups"
echo

# Check disk space
echo "Disk maydoni:"
local available_space=$(df -h . 2>/dev/null | awk 'NR==2 {print $4}' || echo "unknown")
local used_percentage=$(df -h . 2>/dev/null | awk 'NR==2 {print $5}' || echo "unknown")

echo " 💾 Mavjud joy: $available_space"
echo " 📊 Ishlatilgan: $used_percentage"

# Warn if disk is almost full
local used_num="${used_percentage%?}" # Remove % sign
if [[ "$used_num" =~ ^[0-9]+$ ]] && [ "$used_num" -gt 90 ]; then
echo " ⚠️ Disk deyarli to'la!"
elif [[ "$used_num" =~ ^[0-9]+$ ]] && [ "$used_num" -gt 80 ]; then
echo " ⚠️ Disk to'la bo'lib bormoqda"
else
echo " ✅ Disk maydoni yetarli"
fi
echo
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
test_syntax_demo
comprehensive_file_tests
advanced_string_tests
numeric_range_tests
environment_tests
fi

5.3 Case statements

Nazariya

Case statement ko'p variantli tanlovlar uchun ishlatiladi. U bir nechta if-elif zanjirining o'rnini bosadi va kodning o'qilishini osonlashtiradi.

Case statement xususiyatlari:

  • Pattern matching qo'llab-quvvatlaydi
  • Wildcard patterns (*, ?, [...])
  • Multiple patterns (| operatori bilan)
  • Fall-through yo'q (har bir case tugagach, esac ga o'tadi)

Sintaksis:

case $variable in
pattern1)
commands
;;
pattern2|pattern3)
commands
;;
*)
default_commands
;;
esac

Amaliyot

#!/bin/bash

# =====================================
# BASIC CASE STATEMENTS
# =====================================

basic_case_demo() {
echo "=== Asosiy Case Statements ==="

# Simple menu system
echo "Asosiy menu:"
echo "1. Fayllar ro'yxati"
echo "2. Disk maydoni"
echo "3. Tizim ma'lumotlari"
echo "4. Chiqish"
echo

read -p "Tanlovingizni kiriting (1-4): " choice

case $choice in
1)
echo "📁 Fayllar ro'yxati:"
ls -la | head -10
;;
2)
echo "💾 Disk maydoni:"
df -h | head -5
;;
3)
echo "🖥️ Tizim ma'lumotlari:"
echo "OS: $(uname -o)"
echo "Kernel: $(uname -r)"
echo "Uptime: $(uptime -p)"
;;
4)
echo "👋 Xayr!"
;;
*)
echo "❌ Noto'g'ri tanlov: $choice"
echo "Iltimos, 1-4 oralig'ida raqam kiriting"
;;
esac
echo
}

# =====================================
# PATTERN MATCHING WITH CASE
# =====================================

pattern_matching_demo() {
echo "=== Pattern Matching bilan Case ==="

# File type detector
detect_file_type() {
local filename="$1"
echo "Fayl turi aniqlash: '$filename'"

case "$filename" in
*.txt|*.text)
echo " 📄 Matn fayli"
;;
*.pdf)
echo " 📕 PDF hujjat"
;;
*.doc|*.docx)
echo " 📘 Word hujjat"
;;
*.jpg|*.jpeg|*.png|*.gif|*.bmp)
echo " 🖼️ Rasm fayli"
;;
*.mp3|*.wav|*.flac|*.aac)
echo " 🎵 Audio fayl"
;;
*.mp4|*.avi|*.mkv|*.mov)
echo " 🎬 Video fayl"
;;
*.zip|*.rar|*.tar|*.gz|*.7z)
echo " 📦 Arxiv fayli"
;;
*.sh|*.bash)
echo " 🔧 Shell script"
;;
*.py)
echo " 🐍 Python script"
;;
*.js)
echo " 💛 JavaScript fayli"
;;
*.html|*.htm)
echo " 🌐 HTML fayl"
;;
*.css)
echo " 🎨 CSS fayl"
;;
.*)
echo " 👁️ Yashirin fayl"
;;
*/)
echo " 📁 Katalog"
;;
*)
echo " ❓ Noma'lum fayl turi"
;;
esac
}

# Test different file types
local test_files=(
"document.txt"
"photo.jpg"
"music.mp3"
"archive.zip"
"script.sh"
"program.py"
"webpage.html"
".hidden_file"
"folder/"
"unknown_file"
)

for file in "${test_files[@]}"; do
detect_file_type "$file"
echo
done
}

# =====================================
# COMMAND LINE ARGUMENT PROCESSING
# =====================================

argument_processing_demo() {
echo "=== Command Line Argument Processing ==="

# Advanced argument processor
process_arguments() {
local verbose=false
local output_file=""
local input_files=()
local operation=""

while [[ $# -gt 0 ]]; do
case $1 in
-v|--verbose)
verbose=true
echo "Verbose rejim yoqildi"
shift
;;
-o|--output)
if [[ -n $2 && $2 != -* ]]; then
output_file="$2"
echo "Output fayl: $output_file"
shift 2
else
echo "❌ --output uchun fayl nomi kerak"
return 1
fi
;;
-f|--file)
if [[ -n $2 && $2 != -* ]]; then
input_files+=("$2")
echo "Input fayl qo'shildi: $2"
shift 2
else
echo "❌ --file uchun fayl nomi kerak"
return 1
fi
;;
--operation=*)
operation="${1#*=}"
echo "Operatsiya: $operation"
shift
;;
-h|--help)
echo "Yordam:"
echo " -v, --verbose Batafsil chiqarish"
echo " -o, --output FILE Output fayli"
echo " -f, --file FILE Input fayli"
echo " --operation=OP Operatsiya turi"
echo " -h, --help Bu yordam"
return 0
;;
-*)
echo "❌ Noma'lum parametr: $1"
echo "Yordam uchun -h yoki --help ishlatting"
return 1
;;
*)
# Positional argument
input_files+=("$1")
echo "Fayl qo'shildi: $1"
shift
;;
esac
done

# Summary
echo
echo "📋 Argument summary:"
echo " Verbose: $verbose"
echo " Output fayl: ${output_file:-'not set'}"
echo " Input fayllar: ${#input_files[@]} ta"
echo " Operatsiya: ${operation:-'not set'}"

if [[ ${#input_files[@]} -gt 0 ]]; then
echo " Fayllar ro'yxati:"
for file in "${input_files[@]}"; do
echo " - $file"
done
fi
}

# Test argument processing
echo "Test argumentlar bilan:"
process_arguments --verbose -o output.txt -f input1.txt -f input2.txt --operation=process additional_file.txt
echo
}

# =====================================
# SYSTEM SERVICE CONTROLLER
# =====================================

service_controller_demo() {
echo "=== Tizim Xizmatlari Boshqaruvi ==="

# Service controller simulation
service_controller() {
local action="$1"
local service_name="$2"

echo "Xizmat boshqaruvi: $action $service_name"

case "$action" in
start)
echo "🟢 $service_name xizmatini ishga tushirish..."

case "$service_name" in
nginx|apache|httpd)
echo " 🌐 Web server ishga tushirildi"
echo " 📊 Port 80/443 da tinglayapti"
;;
mysql|postgresql|database)
echo " 🗄️ Database server ishga tushirildi"
echo " 📊 Database ulanishlari qabul qilinmoqda"
;;
ssh|sshd)
echo " 🔐 SSH server ishga tushirildi"
echo " 📊 Port 22 da tinglayapti"
;;
*)
echo " ⚙️ $service_name xizmati ishga tushirildi"
;;
esac
;;

stop)
echo "🔴 $service_name xizmatini to'xtatish..."

case "$service_name" in
nginx|apache|httpd)
echo " 🌐 Web server to'xtatildi"
echo " ⚠️ Web sayt mavjud emas"
;;
mysql|postgresql|database)
echo " 🗄️ Database server to'xtatildi"
echo " ⚠️ Database ulanishlari yopildi"
;;
ssh|sshd)
echo " 🔐 SSH server to'xtatildi"
echo " ⚠️ Remote ulanishlar mumkin emas"
;;
*)
echo " ⚙️ $service_name xizmati to'xtatildi"
;;
esac
;;

restart)
echo "🔄 $service_name xizmatini qayta ishga tushirish..."
service_controller stop "$service_name"
echo " ⏳ 2 soniya kutish..."
service_controller start "$service_name"
;;

status)
echo "📊 $service_name xizmati holati:"

case "$service_name" in
nginx|apache|httpd)
echo " 🟢 Faol - 1234 ta ulanish"
echo " 📈 CPU: 2.5%, RAM: 45MB"
;;
mysql|postgresql|database)
echo " 🟢 Faol - 56 ta database ulanish"
echo " 📈 CPU: 15.2%, RAM: 512MB"
;;
ssh|sshd)
echo " 🟢 Faol - 3 ta SSH sessiya"
echo " 📈 CPU: 0.1%, RAM: 8MB"
;;
*)
echo " 🟢 Faol"
echo " 📈 CPU: 1.0%, RAM: 32MB"
;;
esac
;;

enable)
echo "✅ $service_name xizmati auto-start yoqildi"
echo " 🔄 Tizim qayta ishga tushganda avtomatik ishga tushadi"
;;

disable)
echo "❌ $service_name xizmati auto-start o'chirildi"
echo " 🔄 Tizim qayta ishga tushganda avtomatik ishga tushmaydi"
;;

reload)
echo "🔄 $service_name konfiguratsiyasini qayta yuklash..."

case "$service_name" in
nginx|apache|httpd)
echo " ⚙️ Web server konfiguratsiyasi qayta yuklandi"
echo " ✅ Ulanishlar uzilmadi"
;;
*)
echo " ⚙️ $service_name konfiguratsiyasi qayta yuklandi"
;;
esac
;;

*)
echo "❌ Noma'lum action: $action"
echo "Mavjud actionlar: start, stop, restart, status, enable, disable, reload"
return 1
;;
esac

echo
}

# Test service controller# 5. Conditional Statements (Shartli Operatorlar) - To'liq Qo'llanma

## 5.1 If statements

### Nazariya

Shartli operatorlar dastur oqimini boshqarish uchun ishlatiladi. Ular shartlarga qarab turli kod bloklarini bajarish imkonini beradi.

**If statement turlari:**
- `if-then-fi` - oddiy shart
- `if-then-else-fi` - ikki holatli shart
- `if-elif-else-fi` - ko'p holatli shart
- Nested if - ichma-ich shartlar

**Sintaksis:**
```bash
if [ shart ]; then
# kod
elif [ boshqa_shart ]; then
# boshqa kod
else
# default kod
fi

Amaliyot

#!/bin/bash

# =====================================
# BASIC IF STATEMENTS
# =====================================

basic_if_demo() {
echo "=== Asosiy If Statements ==="

# Simple if statement
local age=25
echo "Yosh: $age"

if [ $age -ge 18 ]; then
echo "✅ Siz kattasiz"
fi
echo

# If-else statement
local temperature=15
echo "Harorat: ${temperature}°C"

if [ $temperature -gt 20 ]; then
echo "🌞 Issiq kun"
else
echo "🧥 Sovuq kun"
fi
echo

# Multiple conditions with elif
local score=85
echo "Ball: $score"

if [ $score -ge 90 ]; then
echo "🥇 A'lo bahosi"
elif [ $score -ge 80 ]; then
echo "🥈 Yaxshi bahosi"
elif [ $score -ge 70 ]; then
echo "🥉 Qoniqarli bahosi"
elif [ $score -ge 60 ]; then
echo "📝 O'rtacha bahosi"
else
echo "❌ Yomon bahosi"
fi
echo
}

# =====================================
# FILE AND DIRECTORY TESTS
# =====================================

file_tests_demo() {
echo "=== File va Directory Testlari ==="

# Create test files and directories
mkdir -p test_dir
touch test_file.txt
echo "test content" > test_file.txt
chmod 755 test_file.txt

local file_path="test_file.txt"
local dir_path="test_dir"
local missing_file="missing.txt"

echo "Test ob'ektlari: $file_path, $dir_path"
echo

# File existence tests
echo "Mavjudlik testlari:"
if [ -e "$file_path" ]; then
echo "✅ $file_path mavjud"
else
echo "❌ $file_path mavjud emas"
fi

if [ -f "$file_path" ]; then
echo "✅ $file_path oddiy fayl"
else
echo "❌ $file_path oddiy fayl emas"
fi

if [ -d "$dir_path" ]; then
echo "✅ $dir_path katalog"
else
echo "❌ $dir_path katalog emas"
fi

if [ -e "$missing_file" ]; then
echo "✅ $missing_file mavjud"
else
echo "❌ $missing_file mavjud emas"
fi
echo

# Permission tests
echo "Ruxsat testlari:"
if [ -r "$file_path" ]; then
echo "✅ $file_path o'qilishi mumkin"
else
echo "❌ $file_path o'qilmaydi"
fi

if [ -w "$file_path" ]; then
echo "✅ $file_path ga yozish mumkin"
else
echo "❌ $file_path ga yozib bo'lmaydi"
fi

if [ -x "$file_path" ]; then
echo "✅ $file_path bajarilishi mumkin"
else
echo "❌ $file_path bajarilmaydi"
fi
echo

# File size and age tests
echo "Hajm va vaqt testlari:"
if [ -s "$file_path" ]; then
echo "✅ $file_path bo'sh emas"
echo " Hajm: $(wc -c < "$file_path") bayt"
else
echo "❌ $file_path bo'sh"
fi

# Compare file modification times
if [ "$file_path" -nt "$dir_path" ]; then
echo "✅ $file_path $dir_path dan yangi"
else
echo "❌ $file_path $dir_path dan eski yoki bir xil"
fi
echo

# Cleanup
rm -f test_file.txt
rmdir test_dir
}

# =====================================
# STRING TESTS AND VALIDATION
# =====================================

string_tests_demo() {
echo "=== String Testlari va Validatsiya ==="

# Email validation
validate_email() {
local email="$1"
echo "Email tekshiruvi: '$email'"

if [ -z "$email" ]; then
echo "❌ Email bo'sh"
return 1
elif [[ ! "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "❌ Noto'g'ri email format"
return 1
else
echo "✅ To'g'ri email"
return 0
fi
}

# Phone validation (Uzbekistan format)
validate_phone() {
local phone="$1"
echo "Telefon tekshiruvi: '$phone'"

# Clean phone number
phone="${phone// /}" # Remove spaces
phone="${phone//-/}" # Remove dashes
phone="${phone//(/}" # Remove (
phone="${phone//)/}" # Remove )

if [ -z "$phone" ]; then
echo "❌ Telefon raqami bo'sh"
return 1
elif [[ ${#phone} -lt 9 ]]; then
echo "❌ Telefon raqami juda qisqa"
return 1
elif [[ ! "$phone" =~ ^(\+998|998|8)?[0-9]{9}$ ]]; then
echo "❌ Noto'g'ri telefon format"
return 1
else
echo "✅ To'g'ri telefon raqami"
return 0
fi
}

# Password strength validation
validate_password() {
local password="$1"
local errors=0

echo "Parol kuchi tekshiruvi:"

if [ ${#password} -lt 8 ]; then
echo "❌ Juda qisqa (kamida 8 belgi)"
((errors++))
else
echo "✅ Uzunlik yetarli (${#password} belgi)"
fi

if [[ ! "$password" =~ [A-Z] ]]; then
echo "❌ Katta harf yo'q"
((errors++))
else
echo "✅ Katta harf mavjud"
fi

if [[ ! "$password" =~ [a-z] ]]; then
echo "❌ Kichik harf yo'q"
((errors++))
else
echo "✅ Kichik harf mavjud"
fi

if [[ ! "$password" =~ [0-9] ]]; then
echo "❌ Raqam yo'q"
((errors++))
else
echo "✅ Raqam mavjud"
fi

if [[ ! "$password" =~ [^a-zA-Z0-9] ]]; then
echo "❌ Maxsus belgi yo'q"
((errors++))
else
echo "✅ Maxsus belgi mavjud"
fi

if [ $errors -eq 0 ]; then
echo "🔒 Kuchli parol!"
return 0
else
echo "⚠️ Zaif parol ($errors ta kamchilik)"
return 1
fi
}

# Test validation functions
echo "Validatsiya testlari:"
echo

validate_email "user@example.com"
echo
validate_email "invalid-email"
echo

validate_phone "+998901234567"
echo
validate_phone "90 123 45 67"
echo
validate_phone "invalid"
echo

validate_password "MyStr0ng!Pass"
echo
validate_password "weak"
echo
}

# =====================================
# NESTED IF STATEMENTS
# =====================================

nested_if_demo() {
echo "=== Ichma-ich If Statements ==="

# User access control system
user_access_control() {
local username="$1"
local password="$2"
local resource="$3"

echo "Kirish nazorati: user='$username', resource='$resource'"

# First level: Authentication
if [ "$username" == "admin" ] && [ "$password" == "admin123" ]; then
echo "✅ Admin muvaffaqiyatli kiri"

# Admin has access to everything
echo "✅ Admin barcha resurslarga kirish huquqiga ega"
return 0

elif [ "$username" == "user1" ] && [ "$password" == "pass123" ]; then
echo "✅ User1 muvaffaqiyatli kirdi"

# Second level: Authorization for user1
if [ "$resource" == "read" ]; then
echo "✅ User1 o'qish huquqiga ega"
return 0
elif [ "$resource" == "write" ]; then
echo "❌ User1 yozish huquqiga ega emas"
return 1
else
echo "❌ User1 '$resource' huquqiga ega emas"
return 1
fi

elif [ "$username" == "guest" ]; then
echo "✅ Guest foydalanuvchi"

# Guest doesn't need password but has limited access
if [ "$resource" == "read" ]; then
echo "✅ Guest o'qish huquqiga ega"
return 0
else
echo "❌ Guest faqat o'qish huquqiga ega"
return 1
fi

else
echo "❌ Noto'g'ri username yoki parol"
return 1
fi
}

# Grade calculation with nested conditions
calculate_grade() {
local math_score="$1"
local english_score="$2"
local physics_score="$3"

echo "Baholar: Matematika=$math_score, Ingliz tili=$english_score, Fizika=$physics_score"

# First check if all scores are valid
if [ $math_score -ge 0 ] && [ $math_score -le 100 ] &&
[ $english_score -ge 0 ] && [ $english_score -le 100 ] &&
[ $physics_score -ge 0 ] && [ $physics_score -le 100 ]; then

echo "✅ Barcha baholar to'g'ri diapazonida"

local average=$(( (math_score + english_score + physics_score) / 3 ))
echo "O'rtacha ball: $average"

# Nested conditions for final grade
if [ $average -ge 90 ]; then
echo "🥇 A'lo (Excellent)"

# Check if student excels in all subjects
if [ $math_score -ge 95 ] && [ $english_score -ge 95 ] && [ $physics_score -ge 95 ]; then
echo "🌟 Barcha fanlar bo'yicha a'lo!"
fi

elif [ $average -ge 80 ]; then
echo "🥈 Yaxshi (Good)"

# Check weak subjects
if [ $math_score -lt 80 ] || [ $english_score -lt 80 ] || [ $physics_score -lt 80 ]; then
echo "⚠️ Ba'zi fanlarni yaxshilash kerak"

if [ $math_score -lt 80 ]; then
echo " - Matematikani yaxshilash kerak ($math_score)"
fi
if [ $english_score -lt 80 ]; then
echo " - Ingliz tilini yaxshilash kerak ($english_score)"
fi
if [ $physics_score -lt 80 ]; then
echo " - Fizikani yaxshilash kerak ($physics_score)"
fi
fi

elif [ $average -ge 70 ]; then
echo "📝 Qoniqarli (Satisfactory)"
echo "💡 Ko'proq harakat qiling!"

else
echo "❌ Yomon (Poor)"
echo "⚠️ Jiddiy o'qish kerak!"

# Check which subjects need most attention
local min_score=$math_score
local weak_subject="Matematika"

if [ $english_score -lt $min_score ]; then
min_score=$english_score
weak_subject="Ingliz tili"
fi

if [ $physics_score -lt $min_score ]; then
min_score=$physics_score
weak_subject="Fizika"
fi

echo "Eng zaif fan: $weak_subject ($min_score ball)"
fi

else
echo "❌ Noto'g'ri ball kiritilgan!"
echo "Baholar 0-100 oralig'ida bo'lishi kerak"
return 1
fi
}

# Test nested functions
echo "Kirish nazorati testlari:"
user_access_control "admin" "admin123" "delete"
echo
user_access_control "user1" "pass123" "read"
echo
user_access_control "user1" "pass123" "write"
echo
user_access_control "guest" "" "read"
echo

echo "Baho hisoblagich testlari:"
calculate_grade 95 98 92
echo
calculate_grade 85 78 82
echo
calculate_grade 65 70 68
echo
calculate_grade 45 55 50
echo
}

# =====================================
# ADVANCED CONDITIONS
# =====================================

advanced_conditions_demo() {
echo "=== Murakkab Shartlar ==="

# System health check
system_health_check() {
echo "Tizim sog'ligi tekshiruvi:"

# Get system metrics
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | sed 's/%us,//')
local memory_usage=$(free | awk '/^Mem:/ {printf "%.1f", $3/$2 * 100}')
local disk_usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
local load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')

echo "CPU ishlatilishi: ${cpu_usage:-0}%"
echo "RAM ishlatilishi: ${memory_usage:-0}%"
echo "Disk ishlatilishi: ${disk_usage:-0}%"
echo "Load average: ${load_avg:-0}"
echo

local health_score=100
local warnings=()
local critical_issues=()

# CPU check
if (( $(echo "${cpu_usage:-0} > 90" | bc -l) )); then
critical_issues+=("CPU juda yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 30))
elif (( $(echo "${cpu_usage:-0} > 70" | bc -l) )); then
warnings+=("CPU yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 15))
fi

# Memory check
if (( $(echo "${memory_usage:-0} > 90" | bc -l) )); then
critical_issues+=("RAM juda yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 25))
elif (( $(echo "${memory_usage:-0} > 80" | bc -l) )); then
warnings+=("RAM yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 10))
fi

# Disk check
if [ ${disk_usage:-0} -gt 95 ]; then
critical_issues+=("Disk juda to'la (${disk_usage}%)")
health_score=$((health_score - 35))
elif [ ${disk_usage:-0} -gt 85 ]; then
warnings+=("Disk to'la bo'lib bormoqda (${disk_usage}%)")
health_score=$((health_score - 20))
fi

# Load average check (assuming 4 CPU cores)
if (( $(echo "${load_avg:-0} > 8" | bc -l) )); then
critical_issues+=("Tizim juda yuklanган (load: ${load_avg})")
health_score=$((health_score - 20))
elif (( $(echo "${load_avg:-0} > 4" | bc -l) )); then
warnings+=("Tizim yuklanған (load: ${load_avg})")
health_score=$((health_score - 10))
fi

# Report health status
echo "=== SOGLIQ HISOBOTI ==="

if [ ${#critical_issues[@]} -gt 0 ]; then
echo "🚨 KRITIK MUAMMOLAR:"
for issue in "${critical_issues[@]}"; do
echo " ❌ $issue"
done
echo
fi

if [ ${#warnings[@]} -gt 0 ]; then
echo "⚠️ OGOHLANTIRISHLAR:"
for warning in "${warnings[@]}"; do
echo " ⚠️ $warning"
done
echo
fi

echo "Sog'liq darajasi: $health_score/100"

if [ $health_score -ge 90 ]; then
echo "💚 Tizim sog'lom"
elif [ $health_score -ge 70 ]; then
echo "💛 Tizim qoniqarli holatda"
elif [ $health_score -ge 50 ]; then
echo "🧡 Tizim muammoli"
else
echo "❤️ Tizim kritik holatda"
fi
echo
}

# Backup strategy selector
backup_strategy() {
local file_count="$1"
local total_size="$2" # in MB
local available_space="$3" # in MB
local is_weekend="$4" # true/false

echo "Backup strategiyasi tanlash:"
echo "Fayllar soni: $file_count"
echo "Umumiy hajm: ${total_size}MB"
echo "Mavjud joy: ${available_space}MB"
echo "Dam olish kunemi: $is_weekend"
echo

local strategy=""
local compression_level=""
local schedule=""

# Choose strategy based on conditions
if [ $total_size -gt $available_space ]; then
echo "❌ Yetarli joy yo'q - backup imkonsiz"
return 1
elif [ $file_count -gt 100000 ] || [ $total_size -gt 10000 ]; then
# Large backup
strategy="incremental"
compression_level="high"

if [ "$is_weekend" == "true" ]; then
schedule="full_backup"
echo "📦 Yirik backup - to'liq zaxira nusxa (dam olish kuni)"
else
schedule="incremental_only"
echo "📦 Yirik backup - faqat o'zgarishlar"
fi

elif [ $file_count -gt 10000 ] || [ $total_size -gt 1000 ]; then
# Medium backup
strategy="differential"
compression_level="medium"

if [ "$is_weekend" == "true" ]; then
schedule="differential"
echo "📋 O'rtacha backup - differensial"
else
schedule="quick"
echo "📋 O'rtacha backup - tezkor"
fi

else
# Small backup
strategy="full"
compression_level="low"
schedule="immediate"
echo "📄 Kichik backup - to'liq va tezkor"
fi

# Calculate estimated time
local estimated_minutes
if [ "$compression_level" == "high" ]; then
estimated_minutes=$((total_size / 50)) # ~50MB per minute with high compression
elif [ "$compression_level" == "medium" ]; then
estimated_minutes=$((total_size / 100)) # ~100MB per minute with medium compression
else
estimated_minutes=$((total_size / 200)) # ~200MB per minute with low compression
fi

echo
echo "Tavsiya etilgan strategiya:"
echo " Turi: $strategy"
echo " Siqish darajasi: $compression_level"
echo " Rejalashtirish: $schedule"
echo " Taxminiy vaqt: ${estimated_minutes} daqiqa"

# Additional recommendations
if [ $available_space -lt $((total_size * 2)) ]; then
echo "⚠️ Tavsiya: Ko'proq bo'sh joy ajrating"
fi

if [ "$is_weekend" == "false" ] && [ $estimated_minutes -gt 60 ]; then
echo "⚠️ Tavsiya: Backup ni kechqurun yoki dam olish kuniga o'tkazing"
fi

return 0
}

# Test advanced conditions
echo "Tizim sog'ligi tekshiruvi:"
system_health_check

echo "Backup strategiya testlari:"
backup_strategy 50000 5000 20000 "true"
echo
backup_strategy 1000 500 2000 "false"
echo
backup_strategy 200000 15000 12000 "false"
echo
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_if_demo
file_tests_demo
string_tests_demo
nested_if_demo
advanced_conditions_demo
fi

5.2 Test conditions

Nazariya

Test shartlari bash da [ ], [[ ]], va test buyrug'i orqali amalga oshiriladi. Har birining o'z afzalliklari va ishlatilish joylari bor.

Test operatorlari turlari:

  • File tests - fayl va katalog holati
  • String tests - matn taqqoslashi
  • Numeric tests - raqamli taqqoslash
  • Logical tests - mantiqiy operatsiyalar

Sintaksis farqlari:

  • [ ] - POSIX standart, portable
  • [[ ]] - Bash extended, qo'shimcha imkoniyatlar
  • test - klasik Unix buyrug'i

Amaliyot

#!/bin/bash

# =====================================
# TEST COMMAND VARIATIONS
# =====================================

test_syntax_demo() {
echo "=== Test Buyrug'i Sintaksis Farqlari ==="

local num=42
local str="hello"
local file="test.txt"

echo "O'zgaruvchilar: num=$num, str='$str', file='$file'"
echo

# Create test file
echo "test content" > "$file"

echo "Turli test sintakslari:"

# Using test command
if test $num -eq 42; then
echo "✅ test buyrug'i: $num = 42"
fi

# Using [ ] (same as test)
if [ $num -eq 42 ]; then
echo "✅ [ ] sintaksi: $num = 42"
fi

# Using [[ ]] (bash extended)
if [[ $num -eq 42 ]]; then
echo "✅ [[ ]] sintaksi: $num = 42"
fi
echo

# String comparison differences
echo "String taqqoslash farqlari:"

# [ ] requires quotes for variables
if [ "$str" = "hello" ]; then
echo "✅ [ ] bilan string taqqoslash (qo'shtirnoq kerak)"
fi

# [[ ]] doesn't require quotes (but good practice to use them)
if [[ $str == "hello" ]]; then
echo "✅ [[ ]] bilan string taqqoslash"
fi

# [[ ]] supports pattern matching
if [[ $str == h* ]]; then
echo "✅ [[ ]] pattern matching: '$str' 'h' bilan boshlanadi"
fi

# [[ ]] supports regex
if [[ $str =~ ^h.* ]]; then
echo "✅ [[ ]] regex: '$str' regex ga mos keladi"
fi
echo

# Cleanup
rm -f "$file"
}

# =====================================
# COMPREHENSIVE FILE TESTS
# =====================================

comprehensive_file_tests() {
echo "=== To'liq File Testlari ==="

# Create test environment
mkdir -p test_env
cd test_env

# Create different types of files
echo "regular file content" > regular_file.txt
mkdir directory
touch empty_file
ln -s regular_file.txt symbolic_link
mkfifo named_pipe 2>/dev/null || echo "FIFO yaratib bo'lmadi"

# Make executable file
echo '#!/bin/bash\necho "executable"' > script.sh
chmod +x script.sh

# Create read-only file
echo "read only content" > readonly_file.txt
chmod 444 readonly_file.txt

local files=(
"regular_file.txt"
"directory"
"empty_file"
"symbolic_link"
"named_pipe"
"script.sh"
"readonly_file.txt"
"nonexistent_file"
)

echo "Test ob'ektlari yaratildi"
echo

# Test each file type
for item in "${files[@]}"; do
echo "Testing: $item"

if [ -e "$item" ]; then
echo " ✅ Mavjud (-e)"
else
echo " ❌ Mavjud emas (-e)"
continue
fi

if [ -f "$item" ]; then
echo " 📄 Oddiy fayl (-f)"
elif [ -d "$item" ]; then
echo " 📁 Katalog (-d)"
elif [ -L "$item" ]; then
echo " 🔗 Simbolik link (-L)"
elif [ -p "$item" ]; then
echo " 📡 Named pipe (-p)"
fi

if [ -r "$item" ]; then
echo " 👁️ O'qilishi mumkin (-r)"
else
echo " 🚫 O'qilmaydi (-r)"
fi

if [ -w "$item" ]; then
echo " ✏️ Yozilishi mumkin (-w)"
else
echo " 🔒 Yozilmaydi (-w)"
fi

if [ -x "$item" ]; then
echo " ⚡ Bajarilishi mumkin (-x)"
else
echo " ⏹️ Bajarilmaydi (-x)"
fi

if [ -s "$item" ]; then
echo " 📊 Bo'sh emas (-s), hajm: $(wc -c < "$item" 2>/dev/null || echo "?") bayt"
else
echo " 📭 Bo'sh (-s yo'q)"
fi

echo
done

# File comparison tests
echo "File taqqoslash testlari:"

# Create files for comparison
echo "content1" > file1.txt
sleep 1
echo "content2" > file2.txt
cp file1.txt file1_copy.txt

if [ file1.txt -nt file2.txt ]; then
echo "❌ file1.txt file2.txt dan yangi"
else
echo "✅ file1.txt file2.txt dan eski yoki bir xil"
fi

if [ file2.txt -nt file1.txt ]; then
echo "✅ file2.txt file1.txt dan yangi"
else
echo "❌ file2.txt file1.txt dan eski yoki bir xil"
fi

if [ file1.txt -ef file1_copy.txt ]; then
echo "✅ file1.txt va file1_copy.txt bir xil fayl"
else
echo "❌ file1.txt va file1_copy.txt har xil fayllar"
fi

# Cleanup
cd ..
rm -rf test_env
echo
}

# =====================================
# ADVANCED STRING TESTS
# =====================================

advanced_string_tests() {
echo "=== Murakkab String Testlari ==="

# Test data
local test_strings=(
""
" "
"hello"
"Hello World"
"user@example.com"
"+998901234567"
"192.168.1.1"
"2024-06-24"
"MyPassword123!"
" spaces "
)

echo "Test string lari:"
for i in "${!test_strings[@]}"; do
echo " [$i]: '${test_strings[i]}'"
done
echo

# String length and emptiness tests
echo "Uzunlik va bo'shliq testlari:"
for str in "${test_strings[@]}"; do
echo "String: '${str}'"

if [ -z "$str" ]; then
echo " ✅ Bo'sh string (-z)"
else
echo " ❌ Bo'sh emas (-z), uzunlik: ${#str}"
fi

if [ -n "$str" ]; then
echo " ✅ To'ldirilgan (-n)"
else
echo " ❌ Bo'sh (-n)"
fi

# Check for whitespace-only strings
if [[ "$str" =~ ^[[:space:]]*$ ]]; then
echo " ⚪ Faqat bo'shliqlar"
elif [[ "$str" =~ ^[[:space:]] ]] || [[ "$str" =~ [[:space:]]$ ]]; then
echo " ⚠️ Boshi yoki oxirida bo'shliq bor"
fi

echo
done

# Pattern matching tests
echo "Pattern matching testlari:"

local email="user@example.com"
local phone="+998901234567"
local ip="192.168.1.1"
local date="2024-06-24"
local password="MyPassword123!"

echo "Email validatsiya: '$email'"
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo " ✅ To'g'ri email format"
else
echo " ❌ Noto'g'ri email format"
fi

echo "Telefon validatsiya: '$phone'"
if [[ "$phone" =~ ^\+998[0-9]{9}$ ]]; then
echo " ✅ To'g'ri O'zbekiston telefon raqami"
else
echo " ❌ Noto'g'ri telefon format"
fi

echo "IP address validatsiya: '$ip'"
if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo " ✅ IP address formatiga mos"
# Additional validation for IP ranges
IFS='.' read -ra ADDR <<< "$ip"
local valid_ip=true
for octet in "${ADDR[@]}"; do
if [ "$octet" -gt 255 ]; then
valid_ip=false
break
fi
done

if [ "$valid_ip" = true ]; then
echo " ✅ To'g'ri IP address"
else
echo " ❌ IP address diapazondan tashqari"
fi
else
echo " ❌ Noto'g'ri IP format"
fi

echo "Sana validatsiya: '$date'"
if [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
echo " ✅ ISO sana formatiga mos (YYYY-MM-DD)"

# Extract year, month, day
local year="${date%-*-*}"
local month="${date#*-}"; month="${month%-*}"
local day="${date##*-}"

if [ "$year" -ge 1900 ] && [ "$year" -le 2100 ] &&
[ "$month" -ge 1 ] && [ "$month" -le 12 ] &&
[ "$day" -ge 1 ] && [ "$day" -le 31 ]; then
echo " ✅ To'g'ri sana qiymatlari"
else
echo " ❌ Noto'g'ri sana qiymatlari"
fi
else
echo " ❌ Noto'g'ri sana format"
fi

echo "Parol kuchi: '$password'"
local score=0

if [[ ${#password} -ge 8 ]]; then
echo " ✅ Uzunlik yetarli (${#password} >= 8)"
((score++))
else
echo " ❌ Juda qisqa (${#password} < 8)"
fi

if [[ "$password" =~ [A-Z] ]]; then
echo " ✅ Katta harf mavjud"
((score++))
else
echo " ❌ Katta harf yo'q"
fi

if [[ "$password" =~ [a-z] ]]; then
echo " ✅ Kichik harf mavjud"
((score++))
else
echo " ❌ Kichik harf yo'q"
fi

if [[ "$password" =~ [0-9] ]]; then
echo " ✅ Raqam mavjud"
((score++))
else
echo " ❌ Raqam yo'q"
fi

if [[ "$password" =~ [^a-zA-Z0-9] ]]; then
echo " ✅ Maxsus belgi mavjud"
((score++))
else
echo " ❌ Maxsus belgi yo'q"
fi

echo " 🏆 Parol darajasi: $score/5"
echo
}

# =====================================
# NUMERIC RANGE TESTS
# =====================================

numeric_range_tests() {
echo "=== Raqamli Diapazon Testlari ==="

# Age category function
categorize_age() {
local age="$1"
echo "Yosh kategoriyasi: $age"

if ! [[ "$age" =~ ^[0-9]+$ ]]; then
echo " ❌ Noto'g'ri raqam format"
return 1
fi

if [ "$age" -le 0 ]; then
echo " ❌ Noto'g'ri yosh"
elif [ "$age" -le 2 ]; then
echo " 👶 Chaqaloq (0-2 yosh)"
elif [ "$age" -le 5 ]; then
echo " 🧒 Kichik bola (3-5 yosh)"
elif [ "$age" -le 12 ]; then
echo " 👦 Bola (6-12 yosh)"
elif [ "$age" -le 17 ]; then
echo " 👦 O'smir (13-17 yosh)"
elif [ "$age" -le 25 ]; then
echo " 👨 Yosh katta (18-25 yosh)"
elif [ "$age" -le 40 ]; then
echo " 👨 Katta (26-40 yosh)"
elif [ "$age" -le 60 ]; then
echo " 👨 O'rta yosh (41-60 yosh)"
elif [ "$age" -le 80 ]; then
echo " 👴 Keksa (61-80 yosh)"
else
echo " 👴 Juda keksa (80+ yosh)"
fi
}

# Temperature category
categorize_temperature() {
local temp="$1"
echo "Harorat kategoriyasi: ${temp}°C"

if ! [[ "$temp" =~ ^-?[0-9]+$ ]]; then
echo " ❌ Noto'g'ri harorat format"
return 1
fi

if [ "$temp" -le -30 ]; then
echo " 🧊 Ekstremal sovuq"
elif [ "$temp" -le -10 ]; then
echo " ❄️ Juda sovuq"
elif [ "$temp" -le 0 ]; then
echo " 🌨️ Sovuq"
elif [ "$temp" -le 10 ]; then
echo " 🧥 Salqin"
elif [ "$temp" -le 20 ]; then
echo " 🌤️ Iliq"
elif [ "$temp" -le 30 ]; then
echo " ☀️ Issiq"
elif [ "$temp" -le 40 ]; then
echo " 🔥 Juda issiq"
else
echo " 🌋 Ekstremal issiq"
fi
}

# Grade to GPA conversion
grade_to_gpa() {
local grade="$1"
echo "Baho konvertatsiyasi: $grade"

if ! [[ "$grade" =~ ^[0-9]+$ ]] || [ "$grade" -lt 0 ] || [ "$grade" -gt 100 ]; then
echo " ❌ Baho 0-100 oralig'ida bo'lishi kerak"
return 1
fi

local gpa
local letter_grade

if [ "$grade" -ge 97 ]; then
gpa="4.0"
letter_grade="A+"
elif [ "$grade" -ge 93 ]; then
gpa="4.0"
letter_grade="A"
elif [ "$grade" -ge 90 ]; then
gpa="3.7"
letter_grade="A-"
elif [ "$grade" -ge 87 ]; then
gpa="3.3"
letter_grade="B+"
elif [ "$grade" -ge 83 ]; then
gpa="3.0"
letter_grade="B"
elif [ "$grade" -ge 80 ]; then
gpa="2.7"
letter_grade="B-"
elif [ "$grade" -ge 77 ]; then
gpa="2.3"
letter_grade="C+"
elif [ "$grade" -ge 73 ]; then
gpa="2.0"
letter_grade="C"
elif [ "$grade" -ge 70 ]; then
gpa="1.7"
letter_grade="C-"
elif [ "$grade" -ge 67 ]; then
gpa="1.3"
letter_grade="D+"
elif [ "$grade" -ge 65 ]; then
gpa="1.0"
letter_grade="D"
else
gpa="0.0"
letter_grade="F"
fi

echo " 📊 Letter grade: $letter_grade"
echo " 📈 GPA: $gpa"
}

# Test numeric categorizations
local test_ages=(5 13 18 25 45 70 85)
local test_temps=(-25 -5 5 15 25 35 45)
local test_grades=(65 75 85 90 95 100)

echo "Yosh kategoriya testlari:"
for age in "${test_ages[@]}"; do
categorize_age "$age"
echo
done

echo "Harorat kategoriya testlari:"
for temp in "${test_temps[@]}"; do
categorize_temperature "$temp"
echo
done

echo "Baho konvertatsiya testlari:"
for grade in "${test_grades[@]}"; do
grade_to_gpa "$grade"
echo
done
}

# =====================================
# ENVIRONMENT TESTS
# =====================================

environment_tests() {
echo "=== Environment Testlari ==="

# Check operating system
echo "Operatsion tizim tekshiruvi:"

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
echo "✅ Linux tizim"

# Check distribution
if [ -f /etc/os-release ]; then
source /etc/os-release
echo " 📋 Distributiv: $NAME $VERSION"
fi

# Check if running in container
if [ -f /.dockerenv ]; then
echo " 🐳 Docker container ichida"
elif [ -n "${container:-}" ]; then
echo " 📦 Container ichida: $container"
else
echo " 🖥️ Native Linux"
fi

elif [[ "$OSTYPE" == "darwin"* ]]; then
echo "✅ macOS tizim"
elif [[ "$OSTYPE" == "cygwin" ]]; then
echo "✅ Cygwin (Windows)"
elif [[ "$OSTYPE" == "msys" ]]; then
echo "✅ MSYS (Windows)"
else
echo "❓ Noma'lum tizim: $OSTYPE"
fi
echo

# Check shell capabilities
echo "Shell imkoniyatlari:"

if [ -n "$BASH_VERSION" ]; then
echo "✅ Bash shell, versiya: $BASH_VERSION"

# Check bash version for features
local bash_major="${BASH_VERSION%%.*}"
if [ "$bash_major" -ge 4 ]; then
echo " ✅ Zamonaviy Bash (4.0+) - barcha xususiyatlar mavjud"
else
echo " ⚠️ Eski Bash ($BASH_VERSION) - ba'zi xususiyatlar cheklangan"
fi
else
echo "❌ Bash emas"
fi

# Check important environment variables
echo
echo "Muhim environment o'zgaruvchilar:"

local important_vars=(
"USER:Foydalanuvchi nomi"
"HOME:Uy katalogi"
"PATH:Buyruqlar yo'li"
"SHELL:Default shell"
"TERM:Terminal turi"
"LANG:Til sozlamalari"
"PWD:Joriy katalog"
)

for var_info in "${important_vars[@]}"; do
IFS=':' read -r var_name description <<< "$var_info"
local var_value="${!var_name}"

if [ -n "$var_value" ]; then
echo " ✅ $var_name ($description): $var_value"
else
echo " ❌ $var_name ($description): mavjud emas"
fi
done
echo

# Check user permissions
echo "Foydalanuvchi ruxsatlari:"

if [ "$EUID" -eq 0 ]; then
echo " 🔴 Root foydalanuvchi - to'liq ruxsatlar"
else
echo " 👤 Oddiy foydalanuvchi (UID: $EUID)"

# Check sudo access
if sudo -n true 2>/dev/null; then
echo " ✅ Sudo ruxsati mavjud"
elif command -v sudo >/dev/null; then
echo " ⚠️ Sudo mavjud, lekin ruxsat yo'q"
else
echo " ❌ Sudo mavjud emas"
fi
fi

# Check groups
local user_groups=$(groups 2>/dev/null || echo "unknown")
echo " 👥 Guruhlar: $user_groups"
echo

# Check disk space
echo "Disk maydoni:"
local available_space=$(df -h . 2>/dev/null | awk 'NR==2 {print $4}' || echo "unknown")
local used_percentage=$(df -h . 2>/dev/null | awk 'NR==2 {print $5}' || echo "unknown")

echo " 💾 Mavjud joy: $available_space"
echo " 📊 Ishlatilgan: $used_percentage"

# Warn if disk is almost full
local used_num="${used_percentage%?}" # Remove % sign
if [[ "$used_num" =~ ^[0-9]+$ ]] && [ "$used_num" -gt 90 ]; then
echo " ⚠️ Disk deyarli to'la!"
elif [[ "$used_num" =~ ^[0-9]+$ ]] && [ "$used_num" -gt 80 ]; then
echo " ⚠️ Disk to'la bo'lib bormoqda"
else
echo " ✅ Disk maydoni yetarli"
fi
echo
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
test_syntax_demo
comprehensive_file_tests
advanced_string_tests
numeric_range_tests
environment_tests
fi

5.3 Case statements

Nazariya

Case statement ko'p variantli tanlovlar uchun ishlatiladi. U bir nechta if-elif zanjirining o'rnini bosadi va kodning o'qilishini osonlashtiradi.

Case statement xususiyatlari:

  • Pattern matching qo'llab-quvvatlaydi
  • Wildcard patterns (*, ?, [...])
  • Multiple patterns (| operatori bilan)
  • Fall-through yo'q (har bir case tugagach, esac ga o'tadi)

Sintaksis:

case $variable in
pattern1)
commands
;;
pattern2|pattern3)
commands
;;
*)
default_commands
;;
esac

Amaliyot

#!/bin/bash

# =====================================
# BASIC CASE STATEMENTS
# =====================================

basic_case_demo() {
echo "=== Asosiy Case Statements ==="

# Simple menu system
echo "Asosiy menu:"
echo "1. Fayllar ro'yxati"
echo "2. Disk maydoni"
echo "3. Tizim ma'lumotlari"
echo "4. Chiqish"
echo

read -p "Tanlovingizni kiriting (1-4): " choice

case $choice in
1)
echo "📁 Fayllar ro'yxati:"
ls -la | head -10
;;
2)
echo "💾 Disk maydoni:"
df -h | head -5
;;
3)
echo "🖥️ Tizim ma'lumotlari:"
echo "OS: $(uname -o)"
echo "Kernel: $(uname -r)"
echo "Uptime: $(uptime -p)"
;;
4)
echo "👋 Xayr!"
;;
*)
echo "❌ Noto'g'ri tanlov: $choice"
echo "Iltimos, 1-4 oralig'ida raqam kiriting"
;;
esac
echo
}

# =====================================
# PATTERN MATCHING WITH CASE
# =====================================

pattern_matching_demo() {
echo "=== Pattern Matching bilan Case ==="

# File type detector
detect_file_type() {
local filename="$1"
echo "Fayl turi aniqlash: '$filename'"

case "$filename" in
*.txt|*.text)
echo " 📄 Matn fayli"
;;
*.pdf)
echo " 📕 PDF hujjat"
;;
*.doc|*.docx)
echo " 📘 Word hujjat"
;;
*.jpg|*.jpeg|*.png|*.gif|*.bmp)
echo " 🖼️ Rasm fayli"
;;
*.mp3|*.wav|*.flac|*.aac)
echo " 🎵 Audio fayl"
;;
*.mp4|*.avi|*.mkv|*.mov)
echo " 🎬 Video fayl"
;;
*.zip|*.rar|*.tar|*.gz|*.7z)
echo " 📦 Arxiv fayli"
;;
*.sh|*.bash)
echo " 🔧 Shell script"
;;
*.py)
echo " 🐍 Python script"
;;
*.js)
echo " 💛 JavaScript fayli"
;;
*.html|*.htm)
echo " 🌐 HTML fayl"
;;
*.css)
echo " 🎨 CSS fayl"
;;
.*)
echo " 👁️ Yashirin fayl"
;;
*/)
echo " 📁 Katalog"
;;
*)
echo " ❓ Noma'lum fayl turi"
;;
esac
}

# Test different file types
local test_files=(
"document.txt"
"photo.jpg"
"music.mp3"
"archive.zip"
"script.sh"
"program.py"
"webpage.html"
".hidden_file"
"folder/"
"unknown_file"
)

for file in "${test_files[@]}"; do
detect_file_type "$file"
echo
done
}

# =====================================
# COMMAND LINE ARGUMENT PROCESSING
# =====================================

argument_processing_demo() {
echo "=== Command Line Argument Processing ==="

# Advanced argument processor
process_arguments() {
local verbose=false
local output_file=""
local input_files=()
local operation=""

while [[ $# -gt 0 ]]; do
case $1 in
-v|--verbose)
verbose=true
echo "Verbose rejim yoqildi"
shift
;;
-o|--output)
if [[ -n $2 && $2 != -* ]]; then
output_file="$2"
echo "Output fayl: $output_file"
shift 2
else
echo "❌ --output uchun fayl nomi kerak"
return 1
fi
;;
-f|--file)
if [[ -n $2 && $2 != -* ]]; then
input_files+=("$2")
echo "Input fayl qo'shildi: $2"
shift 2
else
echo "❌ --file uchun fayl nomi kerak"
return 1
fi
;;
--operation=*)
operation="${1#*=}"
echo "Operatsiya: $operation"
shift
;;
-h|--help)
echo "Yordam:"
echo " -v, --verbose Batafsil chiqarish"
echo " -o, --output FILE Output fayli"
echo " -f, --file FILE Input fayli"
echo " --operation=OP Operatsiya turi"
echo " -h, --help Bu yordam"
return 0
;;
-*)
echo "❌ Noma'lum parametr: $1"
echo "Yordam uchun -h yoki --help ishlatting"
return 1
;;
*)
# Positional argument
input_files+=("$1")
echo "Fayl qo'shildi: $1"
shift
;;
esac
done

# Summary
echo
echo "📋 Argument summary:"
echo " Verbose: $verbose"
echo " Output fayl: ${output_file:-'not set'}"
echo " Input fayllar: ${#input_files[@]} ta"
echo " Operatsiya: ${operation:-'not set'}"

if [[ ${#input_files[@]} -gt 0 ]]; then
echo " Fayllar ro'yxati:"
for file in "${input_files[@]}"; do
echo " - $file"
done
fi
}

# Test argument processing
echo "Test argumentlar bilan:"
process_arguments --verbose -o output.txt -f input1.txt -f input2.txt --operation=process additional_file.txt
echo
}

# =====================================
# SYSTEM SERVICE CONTROLLER
# =====================================

service_controller_demo() {
echo "=== Tizim Xizmatlari Boshqaruvi ==="

# Service controller simulation
service_controller() {
local action="$1"
local service_name="$2"

echo "Xizmat boshqaruvi: $action $service_name"

case "$action" in
start)
echo "🟢 $service_name xizmatini ishga tushirish..."

case "$service_name" in
nginx|apache|httpd)
echo " 🌐 Web server ishga tushirildi"
echo " 📊 Port 80/443 da tinglayapti"
;;
mysql|postgresql|database)
echo " 🗄️ Database server ishga tushirildi"
echo " 📊 Database ulanishlari qabul qilinmoqda"
;;
ssh|sshd)
echo " 🔐 SSH server ishga tushirildi"
echo " 📊 Port 22 da tinglayapti"
;;
*)
echo " ⚙️ $service_name xizmati ishga tushirildi"
;;
esac
;;

stop)
echo "🔴 $service_name xizmatini to'xtatish..."

case "$service_name" in
nginx|apache|httpd)
echo " 🌐 Web server to'xtatildi"
echo " ⚠️ Web sayt mavjud emas"
;;
mysql|postgresql|database)
echo " 🗄️ Database server to'xtatildi"
echo " ⚠️ Database ulanishlari yopildi"
;;
ssh|sshd)
echo " 🔐 SSH server to'xtatildi"
echo " ⚠️ Remote ulanishlar mumkin emas"
;;
*)
echo " ⚙️ $service_name xizmati to'xtatildi"
;;
esac
;;

restart)
echo "🔄 $service_name xizmatini qayta ishga tushirish..."
service_controller stop "$service_name"
echo " ⏳ 2 soniya kutish..."
service_controller start "$service_name"
;;

status)
echo "📊 $service_name xizmati holati:"

case "$service_name" in
nginx|apache|httpd)
echo " 🟢 Faol - 1234 ta ulanish"
echo " 📈 CPU: 2.5%, RAM: 45MB"
;;
mysql|postgresql|database)
echo " 🟢 Faol - 56 ta database ulanish"
echo " 📈 CPU: 15.2%, RAM: 512MB"
;;
ssh|sshd)
echo " 🟢 Faol - 3 ta SSH sessiya"
echo " 📈 CPU: 0.1%, RAM: 8MB"
;;
*)
echo " 🟢 Faol"
echo " 📈 CPU: 1.0%, RAM: 32MB"
;;
esac
;;

enable)
echo "✅ $service_name xizmati auto-start yoqildi"
echo " 🔄 Tizim qayta ishga tushganda avtomatik ishga tushadi"
;;

disable)
echo "❌ $service_name xizmati auto-start o'chirildi"
echo " 🔄 Tizim qayta ishga tushganda avtomatik ishga tushmaydi"
;;

reload)
echo "🔄 $service_name konfiguratsiyasini qayta yuklash..."

case "$service_name" in
nginx|apache|httpd)
echo " ⚙️ Web server konfiguratsiyasi qayta yuklandi"
echo " ✅ Ulanishlar uzilmadi"
;;
*)
echo " ⚙️ $service_name konfiguratsiyasi qayta yuklandi"
;;
esac
;;

*)
echo "❌ Noma'lum action: $action"
echo "Mavjud actionlar: start, stop, restart, status, enable, disable, reload"
return 1
;;
esac

echo
}

# Test service controller
local test_services=("nginx" "mysql" "ssh")
local test_actions=("start" "status" "restart" "stop")

for service in "${test_services[@]}"; do
for action in "${test_actions[@]}"; do
service_controller "$action" "$service"
done
echo "═══════════════════════════════════════"
done
}

# =====================================
# LOG LEVEL PROCESSOR
# =====================================

log_processor_demo() {
echo "=== Log Level Processor ==="

# Log processor with different levels
process_log() {
local log_level="$1"
local message="$2"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local caller="${FUNCNAME[1]:-main}"

case "$log_level" in
DEBUG|debug)
if [[ "${DEBUG:-false}" == "true" ]]; then
echo -e "\033[36m[$timestamp] [DEBUG] [$caller] $message\033[0m"
fi
;;
INFO|info)
echo -e "\033[32m[$timestamp] [INFO ] [$caller] $message\033[0m"
;;
WARN|warn|WARNING|warning)
echo -e "\033[33m[$timestamp] [WARN ] [$caller] $message\033[0m"
;;
ERROR|error)
echo -e "\033[31m[$timestamp] [ERROR] [$caller] $message\033[0m" >&2
;;
FATAL|fatal)
echo -e "\033[35m[$timestamp] [FATAL] [$caller] $message\033[0m" >&2
echo -e "\033[35m[$timestamp] [FATAL] Application to'xtatilmoqda...\033[0m" >&2
;;
*)
echo -e "\033[37m[$timestamp] [UNKNOWN] [$caller] $message\033[0m"
echo -e "\033[31m[$timestamp] [ERROR] [$caller] Noma'lum log level: $log_level\033[0m" >&2
;;
esac
}

# Application simulation with different log levels
simulate_application() {
echo "Application log simulation:"
echo

process_log "INFO" "Application ishga tushmoqda..."
process_log "DEBUG" "Konfiguratsiya fayli o'qilmoqda: /etc/app/config.conf"
process_log "INFO" "Database ga ulanish..."
process_log "WARN" "Database ulanish sekin (2.5s)"
process_log "INFO" "Database ulanish muvaffaqiyatli"
process_log "DEBUG" "Cache tizimi ishga tushirilmoqda"
process_log "INFO" "Web server port 8080 da ishga tushdi"
process_log "INFO" "Application tayyor - so'rovlarni qabul qilmoqda"

echo
echo "Foydalanuvchi amallar simulation:"
process_log "INFO" "Yangi foydalanuvchi ro'yxatdan o'tdi: user123"
process_log "DEBUG" "Session yaratildi: sess_abc123xyz"
process_log "WARN" "3 marta noto'g'ri parol kiritildi: user456"
process_log "ERROR" "Database query muvaffaqiyatsiz: connection timeout"
process_log "INFO" "Cache cleared: old entries removed"
process_log "FATAL" "Out of memory: heap space exhausted"
}

# Test with debug off
echo "Debug o'chirilgan holda:"
DEBUG=false simulate_application

echo
echo "═══════════════════════════════════════"
echo "Debug yoqilgan holda:"
DEBUG=true simulate_application
}

# =====================================
# SYSTEM CONFIGURATION VALIDATOR
# =====================================

config_validator_demo() {
echo "=== Tizim Konfiguratsiya Validator ==="

# Configuration validator
validate_config() {
local config_type="$1"
local config_value="$2"

echo "Konfiguratsiya validatsiya: $config_type = '$config_value'"

case "$config_type" in
"port")
case "$config_value" in
[1-9][0-9][0-9][0-9]|[1-5][0-9][0-9][0-9][0-9]|6[0-4][0-9][0-9][0-9]|65[0-4][0-9][0-9]|655[0-2][0-9]|6553[0-5])
if [ "$config_value" -lt 1024 ]; then
echo " ⚠️ Privileged port ($config_value) - root ruxsati kerak"
else
echo " ✅ To'g'ri port raqami: $config_value"
fi
;;
*)
echo " ❌ Noto'g'ri port raqami: $config_value (1-65535 oralig'ida bo'lishi kerak)"
return 1
;;
esac
;;

"log_level")
case "$config_value" in
DEBUG|INFO|WARN|ERROR|FATAL)
echo " ✅ To'g'ri log level: $config_value"
;;
debug|info|warn|error|fatal)
echo " ✅ To'g'ri log level: $config_value (kichik harf)"
;;
*)
echo " ❌ Noto'g'ri log level: $config_value"
echo " Mavjud levellar: DEBUG, INFO, WARN, ERROR, FATAL"
return 1
;;
esac
;;

"database_url")
case "$config_value" in
postgresql://*|postgres://*)
echo " ✅ PostgreSQL database URL"
;;
mysql://*|mysql+pymysql://*)
echo " ✅ MySQL database URL"
;;
sqlite:///*|sqlite:///*)
echo " ✅ SQLite database URL"
;;
mongodb://*|mongodb+srv://*)
echo " ✅ MongoDB database URL"
;;
redis://*|rediss://*)
echo " ✅ Redis URL"
;;
*)
echo " ❌ Noma'lum database URL format: $config_value"
return 1
;;
esac
;;

"memory_limit")
case "$config_value" in
*[Gg])
local size_gb="${config_value%[Gg]}"
if [[ "$size_gb" =~ ^[0-9]+$ ]] && [ "$size_gb" -le 64 ]; then
echo " ✅ Memory limit: ${size_gb}GB"
else
echo " ❌ Juda katta memory limit: $config_value (max 64GB)"
return 1
fi
;;
*[Mm])
local size_mb="${config_value%[Mm]}"
if [[ "$size_mb" =~ ^[0-9]+$ ]] && [ "$size_mb" -ge 64 ]; then
echo " ✅ Memory limit: ${size_mb}MB"
else
echo " ❌ Juda kichik memory limit: $config_value (min 64MB)"
return 1
fi
;;
*)
echo " ❌ Noto'g'ri memory format: $config_value (masalan: 512M, 2G)"
return 1
;;
esac
;;

"environment")
case "$config_value" in
development|dev)
echo " 🔧 Development environment"
echo " ⚠️ Debug rejimi, test ma'lumotlari"
;;
staging|stage)
echo " 🧪 Staging environment"
echo " ⚠️ Test environment, production-like"
;;
production|prod)
echo " 🏭 Production environment"
echo " ✅ Live environment, real ma'lumotlar"
;;
testing|test)
echo " 🧪 Testing environment"
echo " ⚠️ Automated testing environment"
;;
*)
echo " ❌ Noma'lum environment: $config_value"
echo " Mavjud: development, staging, production, testing"
return 1
;;
esac
;;

"ssl_mode")
case "$config_value" in
required|require)
echo " 🔒 SSL majburiy - barcha ulanishlar shifrlangan"
;;
preferred|prefer)
echo " 🔓 SSL ixtiyoriy - SSL bo'lsa ishlatiladi"
;;
disabled|disable|none)
echo " ⚠️ SSL o'chirilgan - shifrlanmagan ulanishlar"
echo " ⚠️ Production da tavsiya etilmaydi!"
;;
*)
echo " ❌ Noto'g'ri SSL rejimi: $config_value"
echo " Mavjud: required, preferred, disabled"
return 1
;;
esac
;;

*)
echo " ❌ Noma'lum konfiguratsiya turi: $config_type"
echo " Qo'llab-quvvatlanadigan turlar: port, log_level, database_url, memory_limit, environment, ssl_mode"
return 1
;;
esac

return 0
}

# Test configurations
local test_configs=(
"port:8080"
"port:443"
"port:99999"
"log_level:INFO"
"log_level:INVALID"
"database_url:postgresql://user:pass@localhost:5432/dbname"
"database_url:invalid://test"
"memory_limit:2G"
"memory_limit:512M"
"memory_limit:100TB"
"environment:production"
"environment:invalid_env"
"ssl_mode:required"
"ssl_mode:invalid_mode"
)

echo "Konfiguratsiya validatsiya testlari:"
echo

local passed=0
local failed=0

for config in "${test_configs[@]}"; do
IFS=':' read -r config_type config_value <<< "$config"

if validate_config "$config_type" "$config_value"; then
((passed++))
else
((failed++))
fi
echo
done

echo "═══════════════════════════════════════"
echo "Test natijalari:"
echo " ✅ Muvaffaqiyatli: $passed"
echo " ❌ Muvaffaqiyatsiz: $failed"
echo " 📊 Jami: $((passed + failed))"
}

# =====================================
# INTERACTIVE CONFIGURATION WIZARD
# =====================================

config_wizard_demo() {
echo "=== Interaktiv Konfiguratsiya Wizard ==="

configuration_wizard() {
echo "🧙 Konfiguratsiya Wizard ga xush kelibsiz!"
echo "Bu wizard sizga application sozlashda yordam beradi."
echo

# Application type selection
echo "1. Qanday application yaratmoqchisiz?"
echo " 1) Web Application"
echo " 2) API Service"
echo " 3) Database Service"
echo " 4) Microservice"
echo

local app_type
while true; do
read -p "Tanlovingiz (1-4): " choice
case $choice in
1)
app_type="web"
echo "✅ Web Application tanlandi"
break
;;
2)
app_type="api"
echo "✅ API Service tanlandi"
break
;;
3)
app_type="database"
echo "✅ Database Service tanlandi"
break
;;
4)
app_type="microservice"
echo "✅ Microservice tanlandi"
break
;;
*)
echo "❌ Iltimos, 1-4 oralig'ida raqam kiriting"
;;
esac
done
echo

# Environment selection
echo "2. Environment ni tanlang:"
echo " 1) Development"
echo " 2) Staging"
echo " 3) Production"
echo

local environment
while true; do
read -p "Environment (1-3): " choice
case $choice in
1)
environment="development"
echo "✅ Development environment"
break
;;
2)
environment="staging"
echo "✅ Staging environment"
break
;;
3)
environment="production"
echo "✅ Production environment"
break
;;
*)
echo "❌ Iltimos, 1-3 oralig'ida raqam kiriting"
;;
esac
done
echo

# Generate configuration based on selections
echo "🔧 Konfiguratsiya yaratilmoqda..."
echo

case "$app_type" in
"web")
case "$environment" in
"development")
echo "📋 Web Application - Development konfiguratsiyasi:"
echo " PORT=3000"
echo " LOG_LEVEL=DEBUG"
echo " DATABASE_URL=sqlite:///dev.db"
echo " SSL_MODE=disabled"
echo " MEMORY_LIMIT=512M"
;;
"staging")
echo "📋 Web Application - Staging konfiguratsiyasi:"
echo " PORT=8080"
echo " LOG_LEVEL=INFO"
echo " DATABASE_URL=postgresql://app:password@staging-db:5432/app_staging"
echo " SSL_MODE=preferred"
echo " MEMORY_LIMIT=1G"
;;
"production")
echo "📋 Web Application - Production konfiguratsiyasi:"
echo " PORT=80"
echo " LOG_LEVEL=WARN"
echo " DATABASE_URL=postgresql://app:${DB_PASSWORD}@prod-db:5432/app_prod"
echo " SSL_MODE=required"
echo " MEMORY_LIMIT=2G"
;;
esac
;;
"api")
case "$environment" in
"development")
echo "📋 API Service - Development konfiguratsiyasi:"
echo " API_PORT=5000"
echo " LOG_LEVEL=DEBUG"
echo " RATE_LIMIT=1000"
echo " AUTH_REQUIRED=false"
;;
"staging"|"production")
echo "📋 API Service - ${environment^} konfiguratsiyasi:"
echo " API_PORT=443"
echo " LOG_LEVEL=INFO"
echo " RATE_LIMIT=100"
echo " AUTH_REQUIRED=true"
echo " SSL_CERT=/etc/ssl/api.crt"
;;
esac
;;
"database")
case "$environment" in
"development")
echo "📋 Database Service - Development konfiguratsiyasi:"
echo " DB_PORT=5432"
echo " MAX_CONNECTIONS=20"
echo " BACKUP_ENABLED=false"
;;
"staging"|"production")
echo "📋 Database Service - ${environment^} konfiguratsiyasi:"
echo " DB_PORT=5432"
echo " MAX_CONNECTIONS=100"
echo " BACKUP_ENABLED=true"
echo " BACKUP_SCHEDULE=0 2 * * *"
;;
esac
;;
"microservice")
echo "📋 Microservice - ${environment^} konfiguratsiyasi:"
echo " SERVICE_PORT=8080"
echo " LOG_LEVEL=INFO"
echo " METRICS_ENABLED=true"
echo " HEALTH_CHECK_PATH=/health"
;;
esac

echo
echo "✅ Konfiguratsiya tayyor!"
echo "💡 Tip: Ushbu konfiguratsiyani .env fayliga saqlashingiz mumkin"
}

# Run configuration wizard
configuration_wizard
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_case_demo
pattern_matching_demo
argument_processing_demo
service_controller_demo
log_processor_demo
config_validator_demo
config_wizard_demo
fi# 5. Conditional Statements (Shartli Operatorlar) - To'liq Qo'llanma

## 5.1 If statements

### Nazariya

Shartli operatorlar dastur oqimini boshqarish uchun ishlatiladi. Ular shartlarga qarab turli kod bloklarini bajarish imkonini beradi.

**If statement turlari:**
- `if-then-fi` - oddiy shart
- `if-then-else-fi` - ikki holatli shart
- `if-elif-else-fi` - ko'p holatli shart
- Nested if - ichma-ich shartlar

**Sintaksis:**
```bash
if [ shart ]; then
# kod
elif [ boshqa_shart ]; then
# boshqa kod
else
# default kod
fi

Amaliyot

#!/bin/bash

# =====================================
# BASIC IF STATEMENTS
# =====================================

basic_if_demo() {
echo "=== Asosiy If Statements ==="

# Simple if statement
local age=25
echo "Yosh: $age"

if [ $age -ge 18 ]; then
echo "✅ Siz kattasiz"
fi
echo

# If-else statement
local temperature=15
echo "Harorat: ${temperature}°C"

if [ $temperature -gt 20 ]; then
echo "🌞 Issiq kun"
else
echo "🧥 Sovuq kun"
fi
echo

# Multiple conditions with elif
local score=85
echo "Ball: $score"

if [ $score -ge 90 ]; then
echo "🥇 A'lo bahosi"
elif [ $score -ge 80 ]; then
echo "🥈 Yaxshi bahosi"
elif [ $score -ge 70 ]; then
echo "🥉 Qoniqarli bahosi"
elif [ $score -ge 60 ]; then
echo "📝 O'rtacha bahosi"
else
echo "❌ Yomon bahosi"
fi
echo
}

# =====================================
# FILE AND DIRECTORY TESTS
# =====================================

file_tests_demo() {
echo "=== File va Directory Testlari ==="

# Create test files and directories
mkdir -p test_dir
touch test_file.txt
echo "test content" > test_file.txt
chmod 755 test_file.txt

local file_path="test_file.txt"
local dir_path="test_dir"
local missing_file="missing.txt"

echo "Test ob'ektlari: $file_path, $dir_path"
echo

# File existence tests
echo "Mavjudlik testlari:"
if [ -e "$file_path" ]; then
echo "✅ $file_path mavjud"
else
echo "❌ $file_path mavjud emas"
fi

if [ -f "$file_path" ]; then
echo "✅ $file_path oddiy fayl"
else
echo "❌ $file_path oddiy fayl emas"
fi

if [ -d "$dir_path" ]; then
echo "✅ $dir_path katalog"
else
echo "❌ $dir_path katalog emas"
fi

if [ -e "$missing_file" ]; then
echo "✅ $missing_file mavjud"
else
echo "❌ $missing_file mavjud emas"
fi
echo

# Permission tests
echo "Ruxsat testlari:"
if [ -r "$file_path" ]; then
echo "✅ $file_path o'qilishi mumkin"
else
echo "❌ $file_path o'qilmaydi"
fi

if [ -w "$file_path" ]; then
echo "✅ $file_path ga yozish mumkin"
else
echo "❌ $file_path ga yozib bo'lmaydi"
fi

if [ -x "$file_path" ]; then
echo "✅ $file_path bajarilishi mumkin"
else
echo "❌ $file_path bajarilmaydi"
fi
echo

# File size and age tests
echo "Hajm va vaqt testlari:"
if [ -s "$file_path" ]; then
echo "✅ $file_path bo'sh emas"
echo " Hajm: $(wc -c < "$file_path") bayt"
else
echo "❌ $file_path bo'sh"
fi

# Compare file modification times
if [ "$file_path" -nt "$dir_path" ]; then
echo "✅ $file_path $dir_path dan yangi"
else
echo "❌ $file_path $dir_path dan eski yoki bir xil"
fi
echo

# Cleanup
rm -f test_file.txt
rmdir test_dir
}

# =====================================
# STRING TESTS AND VALIDATION
# =====================================

string_tests_demo() {
echo "=== String Testlari va Validatsiya ==="

# Email validation
validate_email() {
local email="$1"
echo "Email tekshiruvi: '$email'"

if [ -z "$email" ]; then
echo "❌ Email bo'sh"
return 1
elif [[ ! "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "❌ Noto'g'ri email format"
return 1
else
echo "✅ To'g'ri email"
return 0
fi
}

# Phone validation (Uzbekistan format)
validate_phone() {
local phone="$1"
echo "Telefon tekshiruvi: '$phone'"

# Clean phone number
phone="${phone// /}" # Remove spaces
phone="${phone//-/}" # Remove dashes
phone="${phone//(/}" # Remove (
phone="${phone//)/}" # Remove )

if [ -z "$phone" ]; then
echo "❌ Telefon raqami bo'sh"
return 1
elif [[ ${#phone} -lt 9 ]]; then
echo "❌ Telefon raqami juda qisqa"
return 1
elif [[ ! "$phone" =~ ^(\+998|998|8)?[0-9]{9}$ ]]; then
echo "❌ Noto'g'ri telefon format"
return 1
else
echo "✅ To'g'ri telefon raqami"
return 0
fi
}

# Password strength validation
validate_password() {
local password="$1"
local errors=0

echo "Parol kuchi tekshiruvi:"

if [ ${#password} -lt 8 ]; then
echo "❌ Juda qisqa (kamida 8 belgi)"
((errors++))
else
echo "✅ Uzunlik yetarli (${#password} belgi)"
fi

if [[ ! "$password" =~ [A-Z] ]]; then
echo "❌ Katta harf yo'q"
((errors++))
else
echo "✅ Katta harf mavjud"
fi

if [[ ! "$password" =~ [a-z] ]]; then
echo "❌ Kichik harf yo'q"
((errors++))
else
echo "✅ Kichik harf mavjud"
fi

if [[ ! "$password" =~ [0-9] ]]; then
echo "❌ Raqam yo'q"
((errors++))
else
echo "✅ Raqam mavjud"
fi

if [[ ! "$password" =~ [^a-zA-Z0-9] ]]; then
echo "❌ Maxsus belgi yo'q"
((errors++))
else
echo "✅ Maxsus belgi mavjud"
fi

if [ $errors -eq 0 ]; then
echo "🔒 Kuchli parol!"
return 0
else
echo "⚠️ Zaif parol ($errors ta kamchilik)"
return 1
fi
}

# Test validation functions
echo "Validatsiya testlari:"
echo

validate_email "user@example.com"
echo
validate_email "invalid-email"
echo

validate_phone "+998901234567"
echo
validate_phone "90 123 45 67"
echo
validate_phone "invalid"
echo

validate_password "MyStr0ng!Pass"
echo
validate_password "weak"
echo
}

# =====================================
# NESTED IF STATEMENTS
# =====================================

nested_if_demo() {
echo "=== Ichma-ich If Statements ==="

# User access control system
user_access_control() {
local username="$1"
local password="$2"
local resource="$3"

echo "Kirish nazorati: user='$username', resource='$resource'"

# First level: Authentication
if [ "$username" == "admin" ] && [ "$password" == "admin123" ]; then
echo "✅ Admin muvaffaqiyatli kiri"

# Admin has access to everything
echo "✅ Admin barcha resurslarga kirish huquqiga ega"
return 0

elif [ "$username" == "user1" ] && [ "$password" == "pass123" ]; then
echo "✅ User1 muvaffaqiyatli kirdi"

# Second level: Authorization for user1
if [ "$resource" == "read" ]; then
echo "✅ User1 o'qish huquqiga ega"
return 0
elif [ "$resource" == "write" ]; then
echo "❌ User1 yozish huquqiga ega emas"
return 1
else
echo "❌ User1 '$resource' huquqiga ega emas"
return 1
fi

elif [ "$username" == "guest" ]; then
echo "✅ Guest foydalanuvchi"

# Guest doesn't need password but has limited access
if [ "$resource" == "read" ]; then
echo "✅ Guest o'qish huquqiga ega"
return 0
else
echo "❌ Guest faqat o'qish huquqiga ega"
return 1
fi

else
echo "❌ Noto'g'ri username yoki parol"
return 1
fi
}

# Grade calculation with nested conditions
calculate_grade() {
local math_score="$1"
local english_score="$2"
local physics_score="$3"

echo "Baholar: Matematika=$math_score, Ingliz tili=$english_score, Fizika=$physics_score"

# First check if all scores are valid
if [ $math_score -ge 0 ] && [ $math_score -le 100 ] &&
[ $english_score -ge 0 ] && [ $english_score -le 100 ] &&
[ $physics_score -ge 0 ] && [ $physics_score -le 100 ]; then

echo "✅ Barcha baholar to'g'ri diapazonida"

local average=$(( (math_score + english_score + physics_score) / 3 ))
echo "O'rtacha ball: $average"

# Nested conditions for final grade
if [ $average -ge 90 ]; then
echo "🥇 A'lo (Excellent)"

# Check if student excels in all subjects
if [ $math_score -ge 95 ] && [ $english_score -ge 95 ] && [ $physics_score -ge 95 ]; then
echo "🌟 Barcha fanlar bo'yicha a'lo!"
fi

elif [ $average -ge 80 ]; then
echo "🥈 Yaxshi (Good)"

# Check weak subjects
if [ $math_score -lt 80 ] || [ $english_score -lt 80 ] || [ $physics_score -lt 80 ]; then
echo "⚠️ Ba'zi fanlarni yaxshilash kerak"

if [ $math_score -lt 80 ]; then
echo " - Matematikani yaxshilash kerak ($math_score)"
fi
if [ $english_score -lt 80 ]; then
echo " - Ingliz tilini yaxshilash kerak ($english_score)"
fi
if [ $physics_score -lt 80 ]; then
echo " - Fizikani yaxshilash kerak ($physics_score)"
fi
fi

elif [ $average -ge 70 ]; then
echo "📝 Qoniqarli (Satisfactory)"
echo "💡 Ko'proq harakat qiling!"

else
echo "❌ Yomon (Poor)"
echo "⚠️ Jiddiy o'qish kerak!"

# Check which subjects need most attention
local min_score=$math_score
local weak_subject="Matematika"

if [ $english_score -lt $min_score ]; then
min_score=$english_score
weak_subject="Ingliz tili"
fi

if [ $physics_score -lt $min_score ]; then
min_score=$physics_score
weak_subject="Fizika"
fi

echo "Eng zaif fan: $weak_subject ($min_score ball)"
fi

else
echo "❌ Noto'g'ri ball kiritilgan!"
echo "Baholar 0-100 oralig'ida bo'lishi kerak"
return 1
fi
}

# Test nested functions
echo "Kirish nazorati testlari:"
user_access_control "admin" "admin123" "delete"
echo
user_access_control "user1" "pass123" "read"
echo
user_access_control "user1" "pass123" "write"
echo
user_access_control "guest" "" "read"
echo

echo "Baho hisoblagich testlari:"
calculate_grade 95 98 92
echo
calculate_grade 85 78 82
echo
calculate_grade 65 70 68
echo
calculate_grade 45 55 50
echo
}

# =====================================
# ADVANCED CONDITIONS
# =====================================

advanced_conditions_demo() {
echo "=== Murakkab Shartlar ==="

# System health check
system_health_check() {
echo "Tizim sog'ligi tekshiruvi:"

# Get system metrics
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | sed 's/%us,//')
local memory_usage=$(free | awk '/^Mem:/ {printf "%.1f", $3/$2 * 100}')
local disk_usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
local load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')

echo "CPU ishlatilishi: ${cpu_usage:-0}%"
echo "RAM ishlatilishi: ${memory_usage:-0}%"
echo "Disk ishlatilishi: ${disk_usage:-0}%"
echo "Load average: ${load_avg:-0}"
echo

local health_score=100
local warnings=()
local critical_issues=()

# CPU check
if (( $(echo "${cpu_usage:-0} > 90" | bc -l) )); then
critical_issues+=("CPU juda yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 30))
elif (( $(echo "${cpu_usage:-0} > 70" | bc -l) )); then
warnings+=("CPU yuqori ishlatilmoqda (${cpu_usage}%)")
health_score=$((health_score - 15))
fi

# Memory check
if (( $(echo "${memory_usage:-0} > 90" | bc -l) )); then
critical_issues+=("RAM juda yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 25))
elif (( $(echo "${memory_usage:-0} > 80" | bc -l) )); then
warnings+=("RAM yuqori ishlatilmoqda (${memory_usage}%)")
health_score=$((health_score - 10))
fi

# Disk check
if [ ${disk_usage:-0} -gt 95 ]; then
critical_issues+=("Disk juda to'la (${disk_usage}%)")
health_score=$((health_score - 35))
elif [ ${disk_usage:-0} -gt 85 ]; then
warnings+=("Disk to'la bo'lib bormoqda (${disk_usage}%)")
health_score=$((health_score - 20))
fi

# Load average check (assuming 4 CPU cores)
if (( $(echo "${load_avg:-0} > 8" | bc -l) )); then
critical_issues+=("Tizim juda yuklanган (load: ${load_avg})")
health_score=$((health_score - 20))
elif (( $(echo "${load_avg:-0} > 4" | bc -l) )); then
warnings+=("Tizim yuklanған (load: ${load_avg})")
health_score=$((health_score - 10))
fi

# Report health status
echo "=== SOGLIQ HISOBOTI ==="

if [ ${#critical_issues[@]} -gt 0 ]; then
echo "🚨 KRITIK MUAMMOLAR:"
for issue in "${critical_issues[@]}"; do
echo " ❌ $issue"
done
echo
fi

if [ ${#warnings[@]} -gt 0 ]; then
echo "⚠️ OGOHLANTIRISHLAR:"
for warning in "${warnings[@]}"; do
echo " ⚠️ $warning"
done
echo
fi

echo "Sog'liq darajasi: $health_score/100"

if [ $health_score -ge 90 ]; then
echo "💚 Tizim sog'lom"
elif [ $health_score -ge 70 ]; then
echo "💛 Tizim qoniqarli holatda"
elif [ $health_score -ge 50 ]; then
echo "🧡 Tizim muammoli"
else
echo "❤️ Tizim kritik holatda"
fi
echo
}

# Backup strategy selector
backup_strategy() {
local file_count="$1"
local total_size="$2" # in MB
local available_space="$3" # in MB
local is_weekend="$4" # true/false

echo "Backup strategiyasi tanlash:"
echo "Fayllar soni: $file_count"
echo "Umumiy hajm: ${total_size}MB"
echo "Mavjud joy: ${available_space}MB"
echo "Dam olish kunemi: $is_weekend"
echo

local strategy=""
local compression_level=""
local schedule=""

# Choose strategy based on conditions
if [ $total_size -gt $available_space ]; then
echo "❌ Yetarli joy yo'q - backup imkonsiz"
return 1
elif [ $file_count -gt 100000 ] || [ $total_size -gt 10000 ]; then
# Large backup
strategy="incremental"
compression_level="high"

if [ "$is_weekend" == "true" ]; then
schedule="full_backup"
echo "📦 Yirik backup - to'liq zaxira nusxa (dam olish kuni)"
else
schedule="incremental_only"
echo "📦 Yirik backup - faqat o'zgarishlar"
fi

elif [ $file_count -gt 10000 ] || [ $total_size -gt 1000 ]; then
# Medium backup
strategy="differential"
compression_level="medium"

if [ "$is_weekend" == "true" ]; then
schedule="differential"
echo "📋 O'rtacha backup - differensial"
else
schedule="quick"
echo "📋 O'rtacha backup - tezkor"
fi

else
# Small backup
strategy="full"
compression_level="low"
schedule="immediate"
echo "📄 Kichik backup - to'liq va tezkor"
fi

# Calculate estimated time
local estimated_minutes
if [ "$compression_level" == "high" ]; then
estimated_minutes=$((total_size / 50)) # ~50MB per minute with high compression
elif [ "$compression_level" == "medium" ]; then
estimated_minutes=$((total_size / 100)) # ~100MB per minute with medium compression
else
estimated_minutes=$((total_size / 200)) # ~200MB per minute with low compression
fi

echo
echo "Tavsiya etilgan strategiya:"
echo " Turi: $strategy"
echo " Siqish darajasi: $compression_level"
echo " Rejalashtirish: $schedule"
echo " Taxminiy vaqt: ${estimated_minutes} daqiqa"

# Additional recommendations
if [ $available_space -lt $((total_size * 2)) ]; then
echo "⚠️ Tavsiya: Ko'proq bo'sh joy ajrating"
fi

if [ "$is_weekend" == "false" ] && [ $estimated_minutes -gt 60 ]; then
echo "⚠️ Tavsiya: Backup ni kechqurun yoki dam olish kuniga o'tkazing"
fi

return 0
}

# Test advanced conditions
echo "Tizim sog'ligi tekshiruvi:"
system_health_check

echo "Backup strategiya testlari:"
backup_strategy 50000 5000 20000 "true"
echo
backup_strategy 1000 500 2000 "false"
echo
backup_strategy 200000 15000 12000 "false"
echo
}

# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_if_demo
file_tests_demo
string_tests_demo
nested_if_demo
advanced_conditions_demo
fi

5.2 Test conditions

Nazariya

Test shartlari bash da [ ], [[ ]], va test buyrug'i orqali amalga oshiriladi. Har birining o'z afzalliklari va ishlatilish joylari bor.

Test operatorlari turlari:

  • File tests - fayl va katalog holati
  • String tests - matn taqqoslashi
  • Numeric tests - raqamli taqqoslash
  • Logical tests - mantiqiy operatsiyalar

Sintaksis farqlari:

  • [ ] - POSIX standart, portable
  • [[ ]] - Bash extended, qo'shimcha imkoniyatlar
  • test - klasik Unix buyrug'i

Amaliyot

#!/bin/bash

# =====================================
# TEST COMMAND VARIATIONS
# =====================================

test_syntax_demo() {
echo "=== Test Buyrug'i Sintaksis Farqlari ==="

local num=42
local str="hello"
local file="test.txt"

echo "O'zgaruvchilar: num=$num, str='$str', file='$file'"
echo

# Create test file
echo "test content" > "$file"

echo "Turli test sintakslari:"

# Using test command
if test $num -eq 42; then
echo "✅ test buyrug'i: $num = 42"
fi

# Using [ ] (same as test)
if [ $num -eq 42 ]; then
echo "✅ [ ] sintaksi: $num = 42"
fi

# Using [[ ]] (bash extended)
if [[ $num -eq 42 ]]; then
echo "✅ [[ ]] sintaksi: $num = 42"
fi
echo

# String comparison differences
echo "String taqqoslash farqlari:"

# [ ] requires quotes for variables
if [ "$str" = "hello" ]; then
echo "✅ [ ] bilan string taqqoslash (qo'shtirnoq kerak)"
fi

# [[ ]] doesn't require quotes (but good practice to use them)
if [[ $str == "hello" ]]; then
echo "✅ [[ ]] bilan string taqqoslash"
fi

# [[ ]] supports pattern matching
if [[ $str == h* ]]; then
echo "✅ [[ ]] pattern matching: '$str' 'h' bilan boshlanadi"
fi

# [[ ]] supports regex
if [[ $str =~ ^h.* ]]; then
echo "✅ [[ ]] regex: '$str' regex ga mos keladi"
fi
echo

# Cleanup
rm -f "$file"
}

# =====================================
# COMPREHENSIVE FILE TESTS
# =====================================

comprehensive_file_tests() {
echo "=== To'liq File Testlari ==="

# Create test environment
mkdir -p test_env
cd test_env

# Create different types of files
echo "regular file content" > regular_file.txt
mkdir directory
touch empty_file
ln -s regular_file.txt symbolic_link
mkfifo named_pipe 2>/dev/null || echo "FIFO yaratib bo'lmadi"

# Make executable file
echo '#!/bin/bash\necho "executable"' > script.sh
chmod +x script.sh

# Create read-only file
echo "read only content" > readonly_file.txt
chmod 444 readonly_file.txt

local files=(
"regular_file.txt"
"directory"
"empty_file"
"symbolic_link"
"named_pipe"
"script.sh"
"readonly_file.txt"
"nonexistent_file"
)

echo "Test ob'ektlari yaratildi"
echo

# Test each file type
for item in "${files[@]}"; do
echo "Testing: $item"

if [ -e "$item" ]; then
echo " ✅ Mavjud (-e)"
else
echo " ❌ Mavjud emas (-e)"
continue
fi

if [ -f "$item" ]; then
echo " 📄 Oddiy fayl (-f)"
elif [ -d "$item" ]; then
echo " 📁 Katalog (-d)"
elif [ -L "$item" ]; then
echo " 🔗 Simbolik link (-L)"
elif [ -p "$item" ]; then
echo " 📡 Named pipe (-p)"
fi

if [ -r "$item" ]; then
echo " 👁️ O'qilishi mumkin (-r)"
else
echo " 🚫 O'qilmaydi (-r)"
fi

if [ -w "$item" ]; then
echo " ✏️ Yozilishi mumkin (-w)"
else
echo " 🔒 Yozilmaydi (-w)"
fi

if [ -x "$item" ]; then
echo " ⚡ Bajarilishi mumkin (-x)"
else
echo " ⏹️ Bajarilmaydi (-x)"
fi

if [ -s "$item" ]; then
echo " 📊 Bo'sh emas (-s), hajm: $(wc -c < "$item" 2>/dev/null || echo "?") bayt"
else
echo " 📭 Bo'sh (-s yo'q)"
fi

echo
done

# File comparison tests
echo "File taqqoslash testlari:"

# Create files for comparison
echo "content1" > file1.txt
sleep 1
echo "content2" > file2.txt
cp file1.txt file1_copy.txt

if [ file1.txt -nt file2.txt ]; then
echo "❌ file1.txt file2.txt dan yangi"
else
echo "✅ file1.txt file2.txt dan eski yoki bir xil"
fi

if [ file2.txt -nt file1.txt ]; then
echo "✅ file2.txt file1.txt dan yangi"
else
echo "❌ file2.txt file1.txt dan eski yoki bir xil"
fi

if [ file1.txt -ef file1_copy