Input/Output
3.1 Input methods
Nazariya
Input - bu foydalanuvchi yoki boshqa dasturlardan ma'lumot olish jarayoni. Bash da turli usullar mavjud:
Input turlari:
- Interactive input -
readbuyrug'i orqali - Command line arguments - script ga uzatilgan parametrlar
- File input - fayllardan ma'lumot o'qish
- Pipeline input - boshqa buyruqlardan ma'lumot olish
- Environment variables - tizim o'zgaruvchilaridan
Amaliyot
#!/bin/bash
# =====================================
# BASIC READ OPERATIONS
# =====================================
basic_input_demo() {
echo "=== Asosiy Input Misollari ==="
# Oddiy input
echo "Ismingizni kiriting:"
read user_name
echo "Salom, $user_name!"
echo
# Bir qatorda so'rash
read -p "Yoshingizni kiriting: " user_age
echo "Siz $user_age yoshdasiz"
echo
# Maxfiy input (parol)
read -s -p "Parolni kiriting: " user_password
echo # Yangi qator
echo "Parol uzunligi: ${#user_password} belgi"
echo
# Timeout bilan input
echo "10 soniya ichida ismingizni kiriting:"
if read -t 10 -p "Ism: " timed_name; then
echo "Rahmat, $timed_name!"
else
echo "Vaqt tugadi! Default ism ishlatiladi."
timed_name="Anonymous"
fi
echo
}
# =====================================
# MULTIPLE INPUT VALUES
# =====================================
multiple_input_demo() {
echo "=== Ko'p Qiymatli Input ==="
# Bir nechta qiymat bir vaqtda
echo "Ism va familiyangizni kiriting (bo'shliq bilan ajrating):"
read first_name last_name
echo "To'liq ism: $first_name $last_name"
echo
# Array ga o'qish
echo "Sevimli ranglaringizni kiriting (bo'shliq bilan ajrating):"
read -a colors
echo "Siz ${#colors[@]} ta rang kirtingiz:"
for i in "${!colors[@]}"; do
echo " $((i+1)). ${colors[i]}"
done
echo
# Butun qatorni o'qish
echo "Uzun matn kiriting:"
read -r full_line
echo "Siz yozdingiz: $full_line"
echo
}
# =====================================
# COMMAND LINE ARGUMENTS
# =====================================
command_args_demo() {
echo "=== Command Line Arguments ==="
echo "Script nomi: $0"
echo "Argumentlar soni: $#"
echo
if [[ $# -eq 0 ]]; then
echo "Hech qanday argument berilmagan"
echo "Ishlatish: $0 <arg1> <arg2> ..."
return
fi
echo "Barcha argumentlar: $*"
echo "Argumentlar (array): $@"
echo
# Har bir argumentni alohida ko'rsatish
for i in $(seq 1 $#); do
echo "Argument $i: ${!i}"
done
echo
# Argumentlar ustida tsikl
echo "Argumentlar ustida tsikl:"
for arg in "$@"; do
echo " - $arg"
done
echo
}
# =====================================
# ADVANCED INPUT VALIDATION
# =====================================
validated_input_demo() {
echo "=== Validatsiya bilan Input ==="
# Raqam kiritishni majburlash
while true; do
read -p "Yoshingizni kiriting (raqam): " age_input
if [[ "$age_input" =~ ^[0-9]+$ ]] && [[ $age_input -ge 1 ]] && [[ $age_input -le 120 ]]; then
echo "✅ To'g'ri yosh: $age_input"
break
else
echo "❌ Iltimos, 1-120 oralig'ida raqam kiriting"
fi
done
echo
# Email validatsiyasi
while true; do
read -p "Email manzilingizni kiriting: " email_input
if [[ "$email_input" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "✅ To'g'ri email: $email_input"
break
else
echo "❌ Iltimos, to'g'ri email format kiriting"
fi
done
echo
# Choice selection
echo "Sevimli dasturlash tilini tanlang:"
echo "1) Python"
echo "2) JavaScript"
echo "3) Java"
echo "4) C++"
while true; do
read -p "Tanlovingiz (1-4): " choice
case $choice in
1) echo "✅ Python - ajoyib tanlov!"; break ;;
2) echo "✅ JavaScript - zamonaviy til!"; break ;;
3) echo "✅ Java - kuchli til!"; break ;;
4) echo "✅ C++ - tezkor til!"; break ;;
*) echo "❌ Iltimos, 1-4 oralig'ida raqam kiriting" ;;
esac
done
echo
}
# =====================================
# FILE INPUT
# =====================================
file_input_demo() {
echo "=== File dan Input ==="
# Test fayl yaratish
cat > test_data.txt << EOF
Ahmad Karimov 25
Dilshod Umarov 30
Madina Tosheva 28
Jasur Aliyev 35
EOF
echo "Fayl tarkibi:"
cat test_data.txt
echo
# Faylni qatorma-qator o'qish
echo "Fayldan ma'lumot o'qish:"
while IFS= read -r line; do
# Har bir qatorni bo'laklarga ajratish
read -r name surname age <<< "$line"
echo "Ism: $name, Familiya: $surname, Yosh: $age"
done < test_data.txt
echo
# CSV fayl bilan ishlash
cat > users.csv << EOF
name,age,city
Ahmad,25,Toshkent
Dilshod,30,Samarqand
Madina,28,Buxoro
EOF
echo "CSV fayl bilan ishlash:"
# Header ni o'qish
IFS=',' read -r col1 col2 col3 < users.csv
echo "Ustunlar: $col1, $col2, $col3"
# Ma'lumotlarni o'qish
tail -n +2 users.csv | while IFS=',' read -r name age city; do
echo "👤 $name ($age yosh, $city)"
done
echo
# Cleanup
rm -f test_data.txt users.csv
}
# =====================================
# INTERACTIVE MENU SYSTEM
# =====================================
interactive_menu_demo() {
echo "=== Interaktiv Menu ==="
while true; do
echo
echo "╔══════════════════════════════════════╗"
echo "║ ASOSIY MENU ║"
echo "╠══════════════════════════════════════╣"
echo "║ 1. Tizim ma'lumotlari ║"
echo "║ 2. Disk joy ko'rsatish ║"
echo "║ 3. Jarayonlar ro'yxati ║"
echo "║ 4. Network holatini tekshirish ║"
echo "║ 5. Chiqish ║"
echo "╚══════════════════════════════════════╝"
echo
read -p "Tanlovingizni kiriting (1-5): " menu_choice
case $menu_choice in
1)
echo "📊 Tizim ma'lumotlari:"
echo " OS: $(uname -o)"
echo " Kernel: $(uname -r)"
echo " Uptime: $(uptime -p)"
;;
2)
echo "💾 Disk joy:"
df -h | head -5
;;
3)
echo "⚙️ Top 5 jarayonlar:"
ps aux --sort=-%cpu | head -6
;;
4)
echo "🌐 Network holati:"
if ping -c 1 google.com &>/dev/null; then
echo "✅ Internet mavjud"
else
echo "❌ Internet mavjud emas"
fi
;;
5)
echo "👋 Xayr!"
break
;;
*)
echo "❌ Noto'g'ri tanlov. Iltimos, 1-5 oralig'ida raqam kiriting."
;;
esac
read -p "Davom etish uchun Enter bosing..."
done
}
# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_input_demo
multiple_input_demo
command_args_demo
validated_input_demo
file_input_demo
interactive_menu_demo
fi
3.2 Output methods
Nazariya
Output - bu ma'lumotlarni foydalanuvchiga yoki boshqa dasturlarga uzatish jarayoni. Bash da turli formatlar va yo'nalishlar mavjud.
Output turlari:
- Standard output (stdout) - oddiy natijalar
- Standard error (stderr) - xato xabarlari
- File output - fayllarga yozish
- Formatted output - maxsus formatda chiqarish
- Colored output - rangli matn
Amaliyot
#!/bin/bash
# =====================================
# BASIC OUTPUT METHODS
# =====================================
basic_output_demo() {
echo "=== Asosiy Output Usullari ==="
# echo buyrug'i
echo "Oddiy matn"
echo "Ikki qator" "bitta echo da"
echo -n "Yangi qatorsiz "
echo "davomi"
echo -e "Maxsus belgilar:\nYangi qator\tTab\aBeep"
echo
# printf buyrug'i (formatli)
printf "Formatli chiqarish:\n"
printf "Ism: %s, Yosh: %d, Baho: %.2f\n" "Ahmad" 25 98.75
printf "Raqam formatlash: %05d\n" 42
printf "Protsent: %d%%\n" 85
echo
}
# =====================================
# COLORED OUTPUT
# =====================================
colored_output_demo() {
echo "=== Rangli Output ==="
# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color
echo -e "${RED}Bu qizil matn${NC}"
echo -e "${GREEN}Bu yashil matn${NC}"
echo -e "${YELLOW}Bu sariq matn${NC}"
echo -e "${BLUE}Bu ko'k matn${NC}"
echo
# Background colors
echo -e "\033[41mQizil fon\033[0m"
echo -e "\033[42mYashil fon\033[0m"
echo -e "\033[44mKo'k fon\033[0m"
echo
# Styled text
echo -e "\033[1mQalin matn\033[0m"
echo -e "\033[4mPastiga chizilgan\033[0m"
echo -e "\033[5mMiltillovchi matn\033[0m"
echo
}
# =====================================
# FORMATTED TABLES
# =====================================
formatted_table_demo() {
echo "=== Formatted Jadvallar ==="
# Simple table
printf "%-15s %-8s %-12s\n" "ISM" "YOSH" "SHAHAR"
printf "%-15s %-8s %-12s\n" "---------------" "--------" "------------"
printf "%-15s %-8d %-12s\n" "Ahmad Karimov" 25 "Toshkent"
printf "%-15s %-8d %-12s\n" "Dilshod Umarov" 30 "Samarqand"
printf "%-15s %-8d %-12s\n" "Madina Tosheva" 28 "Buxoro"
echo
# Box drawing characters
echo "╔═══════════════╦════════╦════════════╗"
echo "║ ISM ║ YOSH ║ SHAHAR ║"
echo "╠═══════════════╬════════╬════════════╣"
echo "║ Ahmad Karimov ║ 25 ║ Toshkent ║"
echo "║ Dilshod Umarov║ 30 ║ Samarqand ║"
echo "║ Madina Tosheva║ 28 ║ Buxoro ║"
echo "╚═══════════════╩════════╩════════════╝"
echo
}
# =====================================
# PROGRESS INDICATORS
# =====================================
progress_demo() {
echo "=== Progress Ko'rsatkichlari ==="
# Simple progress bar
echo "Yuklanmoqda..."
for i in {1..20}; do
printf "█"
sleep 0.1
done
echo " 100%"
echo
# Percentage progress
echo "Protsent ko'rsatkichi:"
for i in {0..100..10}; do
printf "\rJarayon: %d%% " $i
printf "["
# Progress bar
for ((j=0; j<i/2; j++)); do printf "="; done
for ((j=i/2; j<50; j++)); do printf " "; done
printf "]"
sleep 0.2
done
echo
echo
# Spinner
echo "Kutib turing..."
spinner='|/-\'
for i in {1..20}; do
printf "\r${spinner:i%4:1} Ishlanmoqda..."
sleep 0.2
done
echo -e "\r✅ Tugadi! "
echo
}
# =====================================
# LOGGING AND TIMESTAMPS
# =====================================
logging_demo() {
echo "=== Logging va Timestamps ==="
# Log levels
log_info() {
echo -e "\033[32m[INFO]\033[0m $(date '+%Y-%m-%d %H:%M:%S') $*"
}
log_warn() {
echo -e "\033[33m[WARN]\033[0m $(date '+%Y-%m-%d %H:%M:%S') $*"
}
log_error() {
echo -e "\033[31m[ERROR]\033[0m $(date '+%Y-%m-%d %H:%M:%S') $*" >&2
}
log_debug() {
if [[ "${DEBUG:-false}" == "true" ]]; then
echo -e "\033[36m[DEBUG]\033[0m $(date '+%Y-%m-%d %H:%M:%S') $*"
fi
}
# Log misollari
log_info "Application ishga tushdi"
log_warn "Konfiguratsiya fayli topilmadi, default qiymatlar ishlatiladi"
log_error "Database ga ulanib bo'lmadi"
DEBUG=true log_debug "Variable qiymati: username=admin"
echo
}
# =====================================
# FILE OUTPUT OPERATIONS
# =====================================
file_output_demo() {
echo "=== File ga Output ==="
# Create test directory
mkdir -p output_test
cd output_test
# Simple file writing
echo "Bu matn faylga yoziladi" > simple.txt
echo "Bu qo'shiladi" >> simple.txt
# Multi-line output
cat > config.txt << EOF
# Application Configuration
app_name=MyApp
version=1.0.0
debug=true
port=8080
EOF
# CSV file creation
cat > users.csv << 'CSV'
name,age,email
Ahmad,25,ahmad@example.com
Dilshod,30,dilshod@example.com
Madina,28,madina@example.com
CSV
# JSON output
cat > data.json << 'JSON'
{
"users": [
{"name": "Ahmad", "age": 25},
{"name": "Dilshod", "age": 30}
],
"total": 2
}
JSON
# Show created files
echo "Yaratilgan fayllar:"
ls -la
echo
echo "simple.txt tarkibi:"
cat simple.txt
echo
# Cleanup
cd ..
rm -rf output_test
}
# =====================================
# REAL-WORLD OUTPUT EXAMPLES
# =====================================
system_report_demo() {
echo "=== Tizim Hisoboti ==="
# Header
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ TIZIM HISOBOTI ║"
echo "║ $(date '+%Y-%m-%d %H:%M:%S') ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo
# System info
printf "%-20s: %s\n" "Tizim" "$(uname -o)"
printf "%-20s: %s\n" "Kernel" "$(uname -r)"
printf "%-20s: %s\n" "Arxitektura" "$(uname -m)"
printf "%-20s: %s\n" "Hostname" "$(hostname)"
printf "%-20s: %s\n" "Uptime" "$(uptime -p)"
echo
# Resource usage
echo "💾 RESURS ISHLATILISHI:"
echo "────────────────────────"
# Memory
local mem_info=$(free -h | awk '/^Mem:/ {print $3 "/" $2}')
printf "%-15s: %s\n" "RAM" "$mem_info"
# Disk
local disk_info=$(df -h / | awk 'NR==2 {print $3 "/" $2 " (" $5 ")"}')
printf "%-15s: %s\n" "Disk (root)" "$disk_info"
# CPU Load
local load_avg=$(uptime | awk -F'load average:' '{print $2}')
printf "%-15s:%s\n" "Load Average" "$load_avg"
echo
# Process count
echo "⚙️ JARAYONLAR:"
echo "──────────────"
printf "%-15s: %d\n" "Jami" "$(ps aux | wc -l)"
printf "%-15s: %d\n" "Foydalanuvchi" "$(ps -u $USER | wc -l)"
printf "%-15s: %d\n" "Running" "$(ps aux | awk '$8=="R"' | wc -l)"
printf "%-15s: %d\n" "Sleeping" "$(ps aux | awk '$8=="S"' | wc -l)"
echo
# Network
echo "🌐 NETWORK:"
echo "────────────"
if ping -c 1 google.com &>/dev/null; then
echo "✅ Internet ulanishi: Faol"
else
echo "❌ Internet ulanishi: Faol emas"
fi
local ip_addr=$(hostname -I | awk '{print $1}')
printf "%-15s: %s\n" "IP Address" "${ip_addr:-N/A}"
echo
}
# Test all functions
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
basic_output_demo
colored_output_demo
formatted_table_demo
progress_demo
logging_demo
file_output_demo
system_report_demo
fi