0% found this document useful (0 votes)
16 views

Bash Script Test A

This script copies all .txt files from a specified directory to a backup subdirectory, then prints a success message. It checks that the given directory exists and lists the .txt files before creating the backup directory and copying the files.

Uploaded by

eran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Bash Script Test A

This script copies all .txt files from a specified directory to a backup subdirectory, then prints a success message. It checks that the given directory exists and lists the .txt files before creating the backup directory and copying the files.

Uploaded by

eran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Exercise 1: File Manipulation

#!/bin/bash

if [ $# -eq 0 ]; then
echo "Usage: $0 <directory>"
exit 1
fi

dir_path="$1"

# Check if the directory exists


if [ ! -d "$dir_path" ]; then
echo "Directory not found: $dir_path"
exit 1
fi

# List all .txt files in the specified directory


txt_files=$(find "$dir_path" -maxdepth 1 -type f -name "*.txt")

# Create a backup directory


backup_dir="$dir_path/backup"
mkdir -p "$backup_dir"

# Copy .txt files to the backup directory


cp $txt_files "$backup_dir"

echo "Backup completed successfully."

Exercise 2: Text Processing


#!/bin/bash

# Read names from the file


names_file="data.txt"
if [ ! -f "$names_file" ]; then
echo "File not found: $names_file"
exit 1
fi

# Count the total number of names


total_names=$(wc -l < "$names_file")

# Display unique names in alphabetical order


echo "Unique names in alphabetical order:"
sort -u "$names_file"

# Prompt user to enter a name


read -p "Enter a name to check: " user_input
# Check if the entered name is in the file
if grep -q "$user_input" "$names_file"; then
echo "Name '$user_input' is in the file."
else
echo "Name '$user_input' is not in the file."
fi

Exercise 3: System Monitoring


#!/bin/bash

# Display current date and time


echo "Current date and time: $(date)"

# Show total number of CPU cores


cpu_cores=$(grep -c '^processor' /proc/cpuinfo)
echo "Total number of CPU cores: $cpu_cores"

# Report free and used memory


free_memory=$(free -h | awk '/^Mem:/ {print $4}')
used_memory=$(free -h | awk '/^Mem:/ {print $3}')
echo "Free memory: $free_memory"
echo "Used memory: $used_memory"

# List top 5 processes consuming the most CPU


echo "Top 5 processes consuming the most CPU:"
ps -eo pid,%cpu,cmd --sort=-%cpu | head -n 6

You might also like