Operators
4.1 Arithmetic operators
Nazariya
Bash da matematik amallarni bajarish uchun bir nechta usul mavjud. Bash aslida string-oriented shell bo'lib, raqamlar ham string sifatida saqlanadi, lekin matematik kontekstda avtomatik konvertatsiya qiladi.
Matematik operatorlar:
+- qo'shish-- ayirish*- ko'paytirish/- bo'lish (butun son)%- qoldiq (modulo)**- daraja++- increment--- decrement
Matematik amallar usullari:
$(( ))- eng keng qo'llaniladiganexpr- eski usulbc- floating point uchunawk- murakkab hisob-kitoblar uchun
Amaliyot
#!/bin/bash
# =====================================
# BASIC ARITHMETIC OPERATIONS
# =====================================
basic_arithmetic_demo() {
echo "=== Asosiy Matematik Amallar ==="
# O'zgaruvchilar
local num1=25
local num2=7
echo "Raqamlar: num1=$num1, num2=$num2"
echo
# Asosiy amallar $(( )) bilan
echo "$(( )) usuli:"
echo " Qo'shish: $num1 + $num2 = $((num1 + num2))"
echo " Ayirish: $num1 - $num2 = $((num1 - num2))"
echo " Ko'paytirish: $num1 * $num2 = $((num1 * num2))"
echo " Bo'lish: $num1 / $num2 = $((num1 / num2))"
echo " Qoldiq: $num1 % $num2 = $((num1 % num2))"
echo " Daraja: $num1 ** 2 = $((num1 ** 2))"
echo
# expr usuli
echo "expr usuli:"
echo " Qo'shish: $(expr $num1 + $num2)"
echo " Ko'paytirish: $(expr $num1 \* $num2)" # * ni escape qilish kerak
echo " Bo'lish: $(expr $num1 / $num2)"
echo
}
# =====================================
# INCREMENT AND DECREMENT
# =====================================
increment_decrement_demo() {
echo "=== Increment va Decrement ==="
local counter=10
echo "Dastlabki qiymat: $counter"
# Pre-increment
echo "Pre-increment: $((++counter))" # Avval oshiradi, keyin qaytaradi
echo "Hozirgi qiymat: $counter"
# Post-increment
echo "Post-increment: $((counter++))" # Avval qaytaradi, keyin oshiradi
echo "Hozirgi qiymat: $counter"
# Pre-decrement
echo "Pre-decrement: $((--counter))"
echo "Hozirgi qiymat: $counter"
# Post-decrement
echo "Post-decrement: $((counter--))"
echo "Hozirgi qiymat: $counter"
echo
# Boshqa usullar
counter=5
echo "Boshqa increment usullari:"
echo " counter += 3: $((counter += 3))" # counter = 8
echo " counter -= 2: $((counter -= 2))" # counter = 6
echo " counter *= 2: $((counter *= 2))" # counter = 12
echo " counter /= 3: $((counter /= 3))" # counter = 4
echo
}
# =====================================
# FLOATING POINT ARITHMETIC
# =====================================
floating_point_demo() {
echo "=== Floating Point Amallar ==="
# bc buyrug'i bilan
local num1=15.75
local num2=4.25
echo "Raqamlar: $num1 va $num2"
echo
# bc bilan hisoblash
echo "bc buyrug'i bilan:"
echo " Qo'shish: $(echo "$num1 + $num2" | bc)"
echo " Ayirish: $(echo "$num1 - $num2" | bc)"
echo " Ko'paytirish: $(echo "$num1 * $num2" | bc)"
echo " Bo'lish: $(echo "scale=2; $num1 / $num2" | bc)"
echo " Daraja: $(echo "$num1 ^ 2" | bc)"
echo " Sqrt: $(echo "sqrt($num1)" | bc -l)"
echo
# awk bilan
echo "awk bilan:"
echo " Qo'shish: $(awk "BEGIN {print $num1 + $num2}")"
echo " Bo'lish: $(awk "BEGIN {printf \"%.2f\", $num1 / $num2}")"
echo " Sin: $(awk "BEGIN {print sin($num1)}")"
echo
}
# =====================================
# MATHEMATICAL FUNCTIONS
# =====================================
math_functions_demo() {
echo "=== Matematik Funksiyalar ==="
# Absolute value
abs_value() {
local num=$1
echo $((num < 0 ? -num : num))
}
# Maximum of two numbers
max_num() {
local a=$1 b=$2
echo $((a > b ? a : b))
}
# Minimum of two numbers
min_num() {
local a=$1 b=$2
echo $((a < b ? a : b))
}
# Power function (integer only)
power() {
local base=$1 exp=$2
local result=1
for ((i=0; i<exp; i++)); do
result=$((result * base))
done
echo $result
}
# Factorial
factorial() {
local num=$1
local result=1
for ((i=1; i<=num; i++)); do
result=$((result * i))
done
echo $result
}
# Test functions
echo "Custom funksiyalar:"
echo " abs(-15) = $(abs_value -15)"
echo " max(25, 18) = $(max_num 25 18)"
echo " min(25, 18) = $(min_num 25 18)"
echo " power(2, 8) = $(power 2 8)"
echo " factorial(5) = $(factorial 5)"
echo
}
# =====================================
# CALCULATOR IMPLEMENTATION
# =====================================
calculator_demo() {
echo "=== Oddiy Kalkulyator ==="
calculator() {
while true; do
echo
echo "╔══════════════════════════════════════╗"
echo "║ KALKULYATOR ║"
echo "╠══════════════════════════════════════╣"
echo "║ 1. Qo'shish (+) ║"
echo "║ 2. Ayirish (-) ║"
echo "║ 3. Ko'paytirish (*) ║"
echo "║ 4. Bo'lish (/) ║"
echo "║ 5. Daraja (**) ║"
echo "║ 6. Qoldiq (%) ║"
echo "║ 7. Chiqish ║"
echo "╚══════════════════════════════════════╝"
echo
read -p "Operatsiyani tanlang (1-7): " operation
if [[ $operation == "7" ]]; then
echo "Kalkulyator yopildi!"
break
fi
read -p "Birinchi sonni kiriting: " num1
read -p "Ikkinchi sonni kiriting: " num2
# Input validation
if ! [[ $num1 =~ ^-?[0-9]+([.][0-9]+)?$ ]] || ! [[ $num2 =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
echo "❌ Iltimos, to'g'ri raqam kiriting!"
continue
fi
case $operation in
1)
if [[ $num1 =~ \. ]] || [[ $num2 =~ \. ]]; then
result=$(echo "$num1 + $num2" | bc)
else
result=$((num1 + num2))
fi
echo "✅ Natija: $num1 + $num2 = $result"
;;
2)
if [[ $num1 =~ \. ]] || [[ $num2 =~ \. ]]; then
result=$(echo "$num1 - $num2" | bc)
else
result=$((num1 - num2))
fi
echo "✅ Natija: $num1 - $num2 = $result"
;;
3)
if [[ $num1 =~ \. ]] || [[ $num2 =~ \. ]]; then
result=$(echo "$num1 * $num2" | bc)
else
result=$((num1 * num2))
fi
echo "✅ Natija: $num1 * $num2 = $result"
;;
4)
if [[ $num2 == "0" ]] || [[ $num2 == "0.0" ]]; then
echo "❌ Xato: Nolga bo'lish mumkin emas!"
else
result=$(echo "scale=4; $num1 / $num2" | bc)
echo "✅ Natija: $num1 / $num2 = $result"
fi
;;
5)
if [[ $num1 =~ \. ]] || [[ $num2 =~ \. ]]; then
result=$(echo "$num1 ^ $num2" | bc -l)
else
result=$((num1 ** num2))
fi
echo "✅ Natija: $num1 ** $num2 = $result"
;;
6)
if [[ $num2 == "0" ]]; then
echo "❌ Xato: Nolga bo'lish mumkin emas!"
else
result=$((num1 % num2))
echo "✅ Natija: $num1 % $num2 = $result"
fi
;;
*)
echo "❌ Noto'g'ri tanlov!"
;;
esac
read -p "Davom etish uchun Enter bosing..."
done
}
# Run calculator
calculator
}
# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_arithmetic_demo
increment_decrement_demo
floating_point_demo
math_functions_demo
echo "Kalkulyatorni ishga tushirish uchun calculator_demo buyrug'ini chaqiring"
fi
4.2 Comparison operators
Nazariya
Taqqoslash operatorlari qiymatlarni solishtirish va mantiqiy natija (true/false) qaytarish uchun ishlatiladi. Bash da turli ma'lumot turlari uchun har xil operatorlar mavjud.
Raqamli taqqoslash:
-eq- equal (teng)-ne- not equal (teng emas)-gt- greater than (katta)-ge- greater or equal (katta yoki teng)-lt- less than (kichik)-le- less or equal (kichik yoki teng)
String taqqoslash:
=yoki==- teng!=- teng emas<- leksikografik jihatdan kichik>- leksikografik jihatdan katta-z- bo'sh string-n- bo'sh emas
Amaliyot
#!/bin/bash
# =====================================
# NUMERIC COMPARISONS
# =====================================
numeric_comparison_demo() {
echo "=== Raqamli Taqqoslashlar ==="
local num1=25
local num2=18
local num3=25
echo "Raqamlar: num1=$num1, num2=$num2, num3=$num3"
echo
# Equality tests
echo "Tenglik testlari:"
if [[ $num1 -eq $num3 ]]; then
echo "✅ $num1 -eq $num3 (teng)"
else
echo "❌ $num1 -eq $num3"
fi
if [[ $num1 -ne $num2 ]]; then
echo "✅ $num1 -ne $num2 (teng emas)"
else
echo "❌ $num1 -ne $num2"
fi
echo
# Comparison tests
echo "Taqqoslash testlari:"
if [[ $num1 -gt $num2 ]]; then
echo "✅ $num1 -gt $num2 ($num1 katta $num2 dan)"
fi
if [[ $num1 -ge $num3 ]]; then
echo "✅ $num1 -ge $num3 ($num1 katta yoki teng $num3 ga)"
fi
if [[ $num2 -lt $num1 ]]; then
echo "✅ $num2 -lt $num1 ($num2 kichik $num1 dan)"
fi
if [[ $num2 -le $num1 ]]; then
echo "✅ $num2 -le $num1 ($num2 kichik yoki teng $num1 ga)"
fi
echo
}
# =====================================
# STRING COMPARISONS
# =====================================
string_comparison_demo() {
echo "=== String Taqqoslashlar ==="
local str1="Ahmad"
local str2="Karimov"
local str3="Ahmad"
local empty_str=""
local space_str=" "
echo "Stringlar:"
echo " str1='$str1'"
echo " str2='$str2'"
echo " str3='$str3'"
echo " empty_str='$empty_str'"
echo " space_str='$space_str'"
echo
# Equality tests
echo "Tenglik testlari:"
if [[ "$str1" == "$str3" ]]; then
echo "✅ '$str1' == '$str3' (teng)"
fi
if [[ "$str1" != "$str2" ]]; then
echo "✅ '$str1' != '$str2' (teng emas)"
fi
echo
# Lexicographic comparison
echo "Leksikografik taqqoslash:"
if [[ "$str1" < "$str2" ]]; then
echo "✅ '$str1' < '$str2' (alifbo tartibida oldin)"
fi
if [[ "$str2" > "$str1" ]]; then
echo "✅ '$str2' > '$str1' (alifbo tartibida keyin)"
fi
echo
# Empty/non-empty tests
echo "Bo'sh/to'ldirilgan testlar:"
if [[ -z "$empty_str" ]]; then
echo "✅ empty_str bo'sh (-z)"
fi
if [[ -n "$str1" ]]; then
echo "✅ str1 to'ldirilgan (-n)"
fi
if [[ -n "$space_str" ]]; then
echo "✅ space_str to'ldirilgan (bo'shliq ham belgi hisoblanadi)"
fi
echo
}
# =====================================
# PATTERN MATCHING
# =====================================
pattern_matching_demo() {
echo "=== Pattern Matching ==="
local filename="document.pdf"
local email="user@example.com"
local phone="+998901234567"
local number="12345"
echo "Ma'lumotlar:"
echo " filename: $filename"
echo " email: $email"
echo " phone: $phone"
echo " number: $number"
echo
# Wildcard patterns
echo "Wildcard patterns:"
if [[ "$filename" == *.pdf ]]; then
echo "✅ '$filename' PDF fayl"
fi
if [[ "$filename" == document.* ]]; then
echo "✅ '$filename' 'document' bilan boshlanadi"
fi
echo
# Regular expressions
echo "Regular expressions:"
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "✅ '$email' to'g'ri email format"
fi
if [[ "$phone" =~ ^\+998[0-9]{9}$ ]]; then
echo "✅ '$phone' to'g'ri O'zbekiston telefon raqami"
fi
if [[ "$number" =~ ^[0-9]+$ ]]; then
echo "✅ '$number' faqat raqamlardan iborat"
fi
echo
}
# =====================================
# ADVANCED COMPARISONS
# =====================================
advanced_comparison_demo() {
echo "=== Murakkab Taqqoslashlar ==="
# Multiple conditions
local age=25
local name="Ahmad"
local salary=5000000
echo "Ma'lumotlar: name=$name, age=$age, salary=$salary"
echo
# Age range check
if [[ $age -ge 18 && $age -le 65 ]]; then
echo "✅ Yosh ishchi yoshi oralig'ida ($age)"
fi
# Name and salary check
if [[ "$name" == "Ahmad" && $salary -gt 3000000 ]]; then
echo "✅ Ahmad va yuqori maosh"
fi
# Complex condition
if [[ ($age -gt 20 && $salary -gt 4000000) || "$name" == "VIP" ]]; then
echo "✅ Premium foydalanuvchi"
fi
echo
# String length comparison
local password="mypassword123"
local min_length=8
local max_length=20
if [[ ${#password} -ge $min_length && ${#password} -le $max_length ]]; then
echo "✅ Parol uzunligi to'g'ri (${#password} belgi)"
fi
echo
}
# =====================================
# VALIDATION FUNCTIONS
# =====================================
validation_demo() {
echo "=== Validatsiya Funksiyalari ==="
# Email validation
is_valid_email() {
local email="$1"
[[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]
}
# Phone validation (Uzbekistan)
is_valid_phone() {
local phone="$1"
# Remove spaces and dashes
phone="${phone// /}"
phone="${phone//-/}"
[[ "$phone" =~ ^\+998[0-9]{9}$ ]]
}
# Age validation
is_valid_age() {
local age="$1"
[[ "$age" =~ ^[0-9]+$ ]] && [[ $age -ge 1 && $age -le 120 ]]
}
# Password strength
is_strong_password() {
local password="$1"
local length=${#password}
# At least 8 characters
[[ $length -ge 8 ]] || return 1
# Contains uppercase
[[ "$password" =~ [A-Z] ]] || return 1
# Contains lowercase
[[ "$password" =~ [a-z] ]] || return 1
# Contains digit
[[ "$password" =~ [0-9] ]] || return 1
# Contains special character
[[ "$password" =~ [^a-zA-Z0-9] ]] || return 1
return 0
}
# Test validation functions
echo "Validatsiya testlari:"
local test_email="user@example.com"
if is_valid_email "$test_email"; then
echo "✅ '$test_email' to'g'ri email"
else
echo "❌ '$test_email' noto'g'ri email"
fi
local test_phone="+998901234567"
if is_valid_phone "$test_phone"; then
echo "✅ '$test_phone' to'g'ri telefon"
else
echo "❌ '$test_phone' noto'g'ri telefon"
fi
local test_age="25"
if is_valid_age "$test_age"; then
echo "✅ '$test_age' to'g'ri yosh"
else
echo "❌ '$test_age' noto'g'ri yosh"
fi
local test_password="MyPass123!"
if is_strong_password "$test_password"; then
echo "✅ Parol kuchli"
else
echo "❌ Parol zaif"
fi
echo
}
# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
numeric_comparison_demo
string_comparison_demo
pattern_matching_demo
advanced_comparison_demo
validation_demo
fi
4.3 Logical operators
Nazariya
Mantiqiy operatorlar bir nechta shartlarni birlashtirish va murakkab mantiqiy ifodalar yaratish uchun ishlatiladi.
Mantiqiy operatorlar:
&&- AND (va) - ikkala shart ham true bo'lishi kerak||- OR (yoki) - kamida biri true bo'lishi kerak!- NOT (emas) - shartni teskarisini qaytaradi
Qisqa baholash (Short-circuit evaluation):
&&da birinchi shart false bo'lsa, ikkinchisi baholanmaydi||da birinchi shart true bo'lsa, ikkinchisi baholanmaydi
Amaliyot
#!/bin/bash
# =====================================
# BASIC LOGICAL OPERATIONS
# =====================================
basic_logical_demo() {
echo "=== Asosiy Mantiqiy Operatorlar ==="
local num=25
local name="Ahmad"
local is_student=true
echo "Ma'lumotlar: num=$num, name='$name', is_student=$is_student"
echo
# AND operator
echo "AND (&&) operatori:"
if [[ $num -gt 20 && "$name" == "Ahmad" ]]; then
echo "✅ num > 20 VA name = Ahmad"
fi
if [[ $num -gt 30 && "$name" == "Ahmad" ]]; then
echo "✅ Bu ko'rsatilmaydi (birinchi shart false)"
else
echo "❌ num > 30 VA name = Ahmad (false)"
fi
echo
# OR operator
echo "OR (||) operatori:"
if [[ $num -gt 30 || "$name" == "Ahmad" ]]; then
echo "✅ num > 30 YOKI name = Ahmad"
fi
if [[ $num -gt 30 || "$name" == "Dilshod" ]]; then
echo "✅ Bu ko'rsatilmaydi"
else
echo "❌ num > 30 YOKI name = Dilshod (false)"
fi
echo
# NOT operator
echo "NOT (!) operatori:"
if [[ ! $num -lt 20 ]]; then
echo "✅ num 20 dan kichik EMAS"
fi
if [[ ! "$name" == "Dilshod" ]]; then
echo "✅ name Dilshod ga teng EMAS"
fi
echo
}
# =====================================
# SHORT-CIRCUIT EVALUATION
# =====================================
short_circuit_demo() {
echo "=== Qisqa Baholash (Short-circuit) ==="
# Function to demonstrate side effects
test_function() {
echo " test_function chaqirildi: $1"
[[ "$1" == "true" ]]
}
echo "AND qisqa baholash:"
echo "false && test_function:"
if [[ 1 -eq 2 ]] && test_function "true"; then
echo " Natija: true"
else
echo " Natija: false (test_function chaqirilmadi)"
fi
echo
echo "true && test_function:"
if [[ 1 -eq 1 ]] && test_function "true"; then
echo " Natija: true"
else
echo " Natija: false"
fi
echo
echo "OR qisqa baholash:"
echo "true || test_function:"
if [[ 1 -eq 1 ]] || test_function "true"; then
echo " Natija: true (test_function chaqirilmadi)"
else
echo " Natija: false"
fi
echo
echo "false || test_function:"
if [[ 1 -eq 2 ]] || test_function "true"; then
echo " Natija: true"
else
echo " Natija: false"
fi
echo
}
# =====================================
# COMPLEX LOGICAL EXPRESSIONS
# =====================================
complex_logical_demo() {
echo "=== Murakkab Mantiqiy Ifodalar ==="
# User data
local age=25
local experience=3
local education="bachelor"
local salary_expected=4000000
local skills=("bash" "python" "sql")
echo "Nomzod ma'lumotlari:"
echo " Yosh: $age"
echo " Tajriba: $experience yil"
echo " Ta'lim: $education"
echo " Kutilgan maosh: $salary_expected"
echo " Ko'nikmalar: ${skills[*]}"
echo
# Job qualification check
echo "Ish o'rinlari uchun mosligi:"
# Junior position
if [[ ($age -ge 20 && $age -le 28) &&
($experience -ge 0 && $experience -le 2) &&
($salary_expected -le 3000000) ]]; then
echo "✅ Junior pozitsiya uchun mos"
else
echo "❌ Junior pozitsiya uchun mos emas"
fi
# Mid-level position
if [[ ($age -ge 23 && $age -le 35) &&
($experience -ge 2 && $experience -le 5) &&
($education == "bachelor" || $education == "master") &&
($salary_expected -le 6000000) ]]; then
echo "✅ Mid-level pozitsiya uchun mos"
else
echo "❌ Mid-level pozitsiya uchun mos emas"
fi
# Senior position
if [[ ($age -ge 28 && $age -le 45) &&
$experience -ge 5 &&
($education == "master" || $education == "phd") &&
($salary_expected -le 10000000) ]]; then
echo "✅ Senior pozitsiya uchun mos"
else
echo "❌ Senior pozitsiya uchun mos emas"
fi
echo
# Skills check
echo "Ko'nikmalar tekshiruvi:"
has_skill() {
local skill="$1"
local found=false
for s in "${skills[@]}"; do
if [[ "$s" == "$skill" ]]; then
found=true
break
fi
done
$found
}
if has_skill "bash" && has_skill "python"; then
echo "✅ DevOps pozitsiya uchun mos (bash + python)"
fi
if has_skill "python" && (has_skill "sql" || has_skill "mongodb"); then
echo "✅ Backend developer uchun mos (python + database)"
fi
if has_skill "javascript" && (has_skill "react" || has_skill "vue"); then
echo "✅ Frontend developer uchun mos"
else
echo "❌ Frontend developer uchun frontend ko'nikmalar yo'q"
fi
echo
}
# =====================================
# PRACTICAL LOGICAL EXAMPLES
# =====================================
practical_logical_demo() {
echo "=== Amaliy Mantiqiy Misollar ==="
# File and directory checks
# File and directory checks
check_environment() {
local config_file="/etc/myapp/config.conf"
local log_dir="/var/log/myapp"
local data_dir="/var/lib/myapp"
local temp_dir="/tmp"
echo "Environment tekshiruvi:"
# Check if all required directories exist
if [[ -d "$log_dir" && -d "$data_dir" && -d "$temp_dir" ]]; then
echo "✅ Barcha kataloglar mavjud"
else
echo "❌ Ba'zi kataloglar mavjud emas:"
[[ ! -d "$log_dir" ]] && echo " - $log_dir"
[[ ! -d "$data_dir" ]] && echo " - $data_dir"
[[ ! -d "$temp_dir" ]] && echo " - $temp_dir"
fi
# Check config file
if [[ -f "$config_file" && -r "$config_file" ]]; then
echo "✅ Konfiguratsiya fayli o'qilishi mumkin"
elif [[ -f "$config_file" && ! -r "$config_file" ]]; then
echo "❌ Konfiguratsiya fayli mavjud, lekin o'qib bo'lmaydi"
else
echo "❌ Konfiguratsiya fayli mavjud emas"
fi
# Check write permissions
if [[ -w "$log_dir" && -w "$data_dir" ]]; then
echo "✅ Log va data kataloglariga yozish mumkin"
else
echo "❌ Ba'zi kataloglarga yozish mumkin emas"
fi
echo
}
# Network connectivity check
check_connectivity() {
local servers=("google.com" "github.com" "stackoverflow.com")
local available_count=0
echo "Network ulanishi tekshiruvi:"
for server in "${servers[@]}"; do
if ping -c 1 -W 3 "$server" &>/dev/null; then
echo "✅ $server - mavjud"
((available_count++))
else
echo "❌ $server - mavjud emas"
fi
done
if [[ $available_count -eq ${#servers[@]} ]]; then
echo "✅ Internet to'liq ishlaydi"
elif [[ $available_count -gt 0 ]]; then
echo "⚠️ Internet qisman ishlaydi ($available_count/${#servers[@]})"
else
echo "❌ Internet ishlamaydi"
fi
echo
}
# Service status check
check_services() {
local services=("ssh" "cron" "systemd-resolved")
local running_count=0
echo "Xizmatlar holati:"
for service in "${services[@]}"; do
if systemctl is-active "$service" &>/dev/null; then
echo "✅ $service - ishlamoqda"
((running_count++))
else
echo "❌ $service - to'xtatilgan"
fi
done
if [[ $running_count -eq ${#services[@]} ]]; then
echo "✅ Barcha xizmatlar ishlamoqda"
elif [[ $running_count -gt 0 ]]; then
echo "⚠️ Ba'zi xizmatlar ishlamaydi ($running_count/${#services[@]})"
else
echo "❌ Hech qanday xizmat ishlamaydi"
fi
echo
}
# Run checks
check_environment
check_connectivity
check_services
}
# =====================================
# USER ACCESS CONTROL
# =====================================
access_control_demo() {
echo "=== Foydalanuvchi Kirish Nazorati ==="
# User authentication simulation
authenticate_user() {
local username="$1"
local password="$2"
local role="$3"
# Predefined users (in real app, this would be from database)
local valid_users=(
"admin:admin123:admin"
"user1:pass123:user"
"user2:secret456:user"
"manager:mgr789:manager"
)
for user_data in "${valid_users[@]}"; do
IFS=':' read -r valid_user valid_pass valid_role <<< "$user_data"
if [[ "$username" == "$valid_user" && "$password" == "$valid_pass" ]]; then
if [[ -n "$role" && "$role" != "$valid_role" ]]; then
echo "❌ Foydalanuvchi mavjud, lekin role mos emas"
return 1
fi
echo "✅ Muvaffaqiyatli kirildi (role: $valid_role)"
return 0
fi
done
echo "❌ Noto'g'ri username yoki parol"
return 1
}
# Permission check
check_permission() {
local user_role="$1"
local required_permission="$2"
case "$user_role" in
"admin")
# Admin has all permissions
echo "✅ Admin - barcha ruxsatlar"
return 0
;;
"manager")
# Manager has read and write, but not delete
if [[ "$required_permission" == "delete" ]]; then
echo "❌ Manager - o'chirish ruxsati yo'q"
return 1
else
echo "✅ Manager - $required_permission ruxsati bor"
return 0
fi
;;
"user")
# User has only read permission
if [[ "$required_permission" == "read" ]]; then
echo "✅ User - o'qish ruxsati bor"
return 0
else
echo "❌ User - faqat o'qish ruxsati bor"
return 1
fi
;;
*)
echo "❌ Noma'lum role"
return 1
;;
esac
}
# Access control workflow
access_workflow() {
local username="$1"
local password="$2"
local action="$3"
echo "Kirish nazorati workflow:"
echo " Username: $username"
echo " Action: $action"
echo
# Step 1: Authentication
if ! authenticate_user "$username" "$password"; then
echo "Kirish rad etildi - authentication muvaffaqiyatsiz"
return 1
fi
# Get user role (simplified - in real app would query database)
local user_role
case "$username" in
"admin") user_role="admin" ;;
"manager") user_role="manager" ;;
*) user_role="user" ;;
esac
# Step 2: Authorization
if ! check_permission "$user_role" "$action"; then
echo "Harakat rad etildi - ruxsat yo'q"
return 1
fi
echo "✅ Harakat ruxsat etildi"
return 0
}
# Test different scenarios
echo "Test senariylari:"
echo
echo "1. Admin foydalanuvchi - delete action:"
access_workflow "admin" "admin123" "delete"
echo
echo "2. Manager foydalanuvchi - write action:"
access_workflow "manager" "mgr789" "write"
echo
echo "3. Manager foydalanuvchi - delete action:"
access_workflow "manager" "mgr789" "delete"
echo
echo "4. Oddiy foydalanuvchi - read action:"
access_workflow "user1" "pass123" "read"
echo
echo "5. Oddiy foydalanuvchi - write action:"
access_workflow "user1" "pass123" "write"
echo
echo "6. Noto'g'ri parol:"
access_workflow "admin" "wrongpass" "read"
echo
}
# =====================================
# CONFIGURATION VALIDATOR
# =====================================
config_validator_demo() {
echo "=== Konfiguratsiya Validator ==="
# Sample configuration
declare -A config=(
["app_name"]="MyWebApp"
["version"]="2.1.0"
["port"]="8080"
["database_host"]="localhost"
["database_port"]="5432"
["database_name"]="myapp_db"
["max_connections"]="100"
["log_level"]="INFO"
["enable_ssl"]="true"
["ssl_cert_path"]="/etc/ssl/certs/app.crt"
["ssl_key_path"]="/etc/ssl/private/app.key"
)
# Validation functions
validate_port() {
local port="$1"
[[ "$port" =~ ^[0-9]+$ ]] && [[ $port -ge 1 && $port -le 65535 ]]
}
validate_log_level() {
local level="$1"
[[ "$level" =~ ^(DEBUG|INFO|WARN|ERROR)$ ]]
}
validate_boolean() {
local value="$1"
[[ "$value" =~ ^(true|false)$ ]]
}
validate_file_exists() {
local file_path="$1"
[[ -f "$file_path" ]]
}
# Main validation
validate_config() {
local errors=0
local warnings=0
echo "Konfiguratsiya tekshiruvi:"
echo
# Required fields check
local required_fields=("app_name" "version" "port" "database_host")
for field in "${required_fields[@]}"; do
if [[ -z "${config[$field]:-}" ]]; then
echo "❌ Majburiy maydon yo'q: $field"
((errors++))
else
echo "✅ $field: ${config[$field]}"
fi
done
echo
# Port validation
if [[ -n "${config[port]:-}" ]]; then
if validate_port "${config[port]}"; then
echo "✅ Port to'g'ri: ${config[port]}"
else
echo "❌ Noto'g'ri port: ${config[port]}"
((errors++))
fi
fi
# Database port validation
if [[ -n "${config[database_port]:-}" ]]; then
if validate_port "${config[database_port]}"; then
echo "✅ Database port to'g'ri: ${config[database_port]}"
else
echo "❌ Noto'g'ri database port: ${config[database_port]}"
((errors++))
fi
fi
# Log level validation
if [[ -n "${config[log_level]:-}" ]]; then
if validate_log_level "${config[log_level]}"; then
echo "✅ Log level to'g'ri: ${config[log_level]}"
else
echo "❌ Noto'g'ri log level: ${config[log_level]}"
((errors++))
fi
fi
# SSL validation
if [[ "${config[enable_ssl]:-false}" == "true" ]]; then
echo "SSL yoqilgan - sertifikatlar tekshirilmoqda:"
if [[ -n "${config[ssl_cert_path]:-}" ]] && validate_file_exists "${config[ssl_cert_path]}"; then
echo "✅ SSL sertifikat topildi: ${config[ssl_cert_path]}"
else
echo "❌ SSL sertifikat fayli topilmadi: ${config[ssl_cert_path]:-'not_set'}"
((errors++))
fi
if [[ -n "${config[ssl_key_path]:-}" ]] && validate_file_exists "${config[ssl_key_path]}"; then
echo "✅ SSL key topildi: ${config[ssl_key_path]}"
else
echo "❌ SSL key fayli topilmadi: ${config[ssl_key_path]:-'not_set'}"
((errors++))
fi
else
echo "⚠️ SSL o'chirilgan - ishlab chiqarishda yoqish tavsiya etiladi"
((warnings++))
fi
# Connection limits
if [[ -n "${config[max_connections]:-}" ]]; then
local max_conn="${config[max_connections]}"
if [[ "$max_conn" =~ ^[0-9]+$ ]]; then
if [[ $max_conn -lt 10 ]]; then
echo "⚠️ Juda kam connection limit: $max_conn"
((warnings++))
elif [[ $max_conn -gt 1000 ]]; then
echo "⚠️ Juda ko'p connection limit: $max_conn"
((warnings++))
else
echo "✅ Connection limit maqbul: $max_conn"
fi
else
echo "❌ Noto'g'ri connection limit: $max_conn"
((errors++))
fi
fi
echo
echo "Tekshiruv natijasi:"
echo " Xatolar: $errors"
echo " Ogohlantirishlar: $warnings"
if [[ $errors -eq 0 && $warnings -eq 0 ]]; then
echo "🎉 Konfiguratsiya mukammal!"
return 0
elif [[ $errors -eq 0 ]]; then
echo "✅ Konfiguratsiya to'g'ri (ba'zi ogohlantirishlar bor)"
return 0
else
echo "❌ Konfiguratsiyada xatolar bor"
return 1
fi
}
validate_config
}
# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_logical_demo
short_circuit_demo
complex_logical_demo
practical_logical_demo
access_control_demo
config_validator_demo
fi