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

Bash Script Exercises

Uploaded by

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

Bash Script Exercises

Uploaded by

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

Bash Script Exercises

please provide my 50 most exercices for bash script to automate most tasks efficiently and cool

Here are 50 Bash scripting exercises to help you master automation efficiently and explore cool use
cases. They are categorized based on difficulty and practical usage:

Basic Exercises (For Starters)

1. Write a script to display "Hello, World!" on the terminal.


2. Create a script to list all files and directories in the current directory.
3. Write a script to take user input and display it as "Welcome, [Name]!"
4. Create a script to check if a file exists and display its size.
5. Write a script to count the number of lines, words, and characters in a text file.
6. Automate the process of creating 10 empty files named `file1` to `file10`.
7. Write a script to find the current system date, time, and uptime.
8. Automate the backup of a folder to a compressed `.tar.gz` archive.
9. Create a script to display the IP address of the machine.
10. Write a script to check if a given process is running (e.g., `nginx`).

Intermediate Exercises (Practical Automation)

11. Automate user creation with a default password and set expiry for the account.
12. Write a script to monitor disk usage and send an alert if it exceeds 80%.
13. Automate searching for specific text in log files (e.g., `/var/log/syslog`).
14. Create a script to rename all `.txt` files in a directory to `.bak`.
15. Write a script to schedule a cron job for daily system updates.
16. Automate downloading a file from a URL and verifying its checksum.
17. Create a script to extract all email addresses from a given text file.
18. Automate the generation of SSH keys and configure them for remote login.
19. Write a script to monitor a folder and log any changes to its contents.
20. Automate setting up a simple HTTP server using Python or `python3 -m http.server`.

Advanced Exercises (Cool and Efficient Tasks)

21. Create a script to monitor CPU usage and kill processes exceeding a set limit.
22. Automate archiving log files older than 7 days in `/var/log`.
23. Write a script to find and delete duplicate files in a directory.
24. Automate database backups for MySQL/MongoDB and encrypt them with GPG.
25. Create a menu-driven script for common system tasks (e.g., user creation, updates).
26. Write a script to check for open ports on the system and save the results.
27. Automate setting up a LAMP/LEMP stack (Linux, Apache/nginx, MySQL, PHP).

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/8
28. Create a script to detect the largest files on the system and move them to a folder.
29. Write a script to automate Git operations (add, commit, push).
30. Automate transferring files between machines using SCP or Rsync.

Scripting with Networking and Security

31. Write a script to scan a network for active hosts (basic port scanning).
32. Automate detecting and blocking IP addresses with too many failed SSH login attempts.
33. Create a script to set up a simple firewall with `iptables` rules.
34. Automate capturing network traffic using `tcpdump` and save it to a file.
35. Write a script to monitor SSL certificate expiry dates for a list of domains.
36. Automate downloading, extracting, and analyzing website data with `wget` or `curl`.
37. Create a script to configure a static IP address for a machine.
38. Automate setting up VPN connections using OpenVPN.

Text Processing and Data Handling

39. Write a script to automate converting `.csv` files to `.json` using Bash tools.
40. Automate finding and replacing text in multiple files using `sed` or `awk`.
41. Create a script to sort a large text file and remove duplicates.
42. Write a script to split a text file into smaller chunks based on line count.
43. Automate generating random passwords and saving them securely.
44. Create a script to parse and display specific fields from a CSV file.

Customizing System Tasks

45. Automate creating a custom Bash prompt (`PS1`) with system info.
46. Write a script to monitor system resource usage and log hourly reports.
47. Automate creating user-specific aliases and adding them to `.bashrc`.
48. Create a script to automatically clean up temporary files every day.
49. Automate installing and updating packages for a list of software (e.g., `apt-get` or `yum`).
50. Write a script to fetch weather information from an API and display it neatly.

How to Approach the Exercises:

1. Start small: Pick 2-3 exercises daily and solve them.


2. Use comments: Add comments to your scripts for better understanding.
3. Test in safe environments: If the script modifies files or users, test in virtual environments.
4. Iterate: Refactor your scripts for readability and performance.

Would you like me to elaborate on any specific exercise or help you get started with one of them?

resolve each exercices you have give me

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/8
Bash Scripting Exercises
# Exercise 1: Display "Hello, World!"
echo "Hello, World!"

# Exercise 2: List all files and directories


ls -la

# Exercise 3: Take user input and display a message


read -p "Enter your name: " name
echo "Welcome, $name!"

# Exercise 4: Check if a file exists and display its size


read -p "Enter file name: " filename
if [ -e "$filename" ]; then
echo "File exists. Size: $(stat -c%s "$filename") bytes"
else
echo "File does not exist."
fi

# Exercise 5: Count lines, words, and characters in a text file


The
readBash script solutions
-p "Enter for"all
file name: 50 exercises have been compiled into
filename a file. Let me know if you'd like me
wc "$filename"
to expand on or explain any specific exercise!
# Exercise 6: Create 10 empty files
for i in {1..10}; do
touch "file$i"
done
make for me , full cours to understand and master awk under linux
# Exercise 7: Display system date, time, and uptime
echo "Date: $(date)"
echo "Uptime: $(uptime -p)"

Here’s a comprehensive
# Exercise course to help you understand and master `awk` under Linux. The course is
8: Backup a folder
divided into modules, progressing
read -p "Enter folder name from basics
to backup: to advanced concepts.
" folder
tar -czf backup_$(date +%F).tar.gz "$folder"

Module 1: 9:
# Exercise Introduction to `awk`
Display IP address

1. What is `awk`?
A programming language for pattern scanning and processing.
Commonly used for text processing and data extraction.
2. Basic Syntax

bash

awk 'pattern {action}' file

`pattern`: Defines when the action should be performed.


`{action}`: The operation to perform on matching lines.
3. First Example

bash

awk '{print $1}' file.txt

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/8
Prints the first column of `file.txt`.
4. Key Features
Field and record-based processing.
In-built variables and operators.
Support for regex.

Module 2: Getting Started

1. Field Separator

bash

awk -F':' '{print $1}' /etc/passwd

`-F':'`: Sets the field separator to `:`.


2. Built-in Variables
`$0`:Entire line.
`$1, $2, ...`: Fields in a record.
`NF`: Number of fields.
`NR`: Current record number.
`FS`: Input field separator.
3. Example: Print Line Numbers

bash

awk '{print NR, $0}' file.txt

Module 3: Patterns

1. Matching Patterns

bash

awk '/pattern/ {print $0}' file.txt

Prints lines containing "pattern".


2. Negating Patterns

bash

awk '!/pattern/ {print $0}' file.txt

Prints lines that do not contain "pattern".


3. Using Multiple Patterns

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/8
bash

awk '/error/ || /warning/ {print $0}' log.txt

Module 4: Actions

1. Print

bash

awk '{print $1, $3}' file.txt

2. Formatting Output

bash

awk '{printf "Name: %s, Age: %d\n", $1, $2}' file.txt

3. Arithmetic Operations

bash

awk '{print $1, $2 * $3}' data.txt

4. Example: Sum of a Column

bash

awk '{sum += $2} END {print "Total:", sum}' data.txt

Module 5: Control Structures

1. `if-else`

bash

awk '{if ($3 > 50) print $1, $3; else print $1, "Fail"}' scores.txt

2. `for` Loops

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/8
bash

awk '{for (i=1; i<=NF; i++) print $i}' file.txt

3. `while` Loops

bash

awk '{i=1; while (i<=NF) {print $i; i++}}' file.txt

Module 6: Functions

1. Built-in Functions
String Functions:

bash

awk '{print toupper($1)}' file.txt

Math Functions:

bash

awk '{print sqrt($2)}' numbers.txt

2. User-Defined Functions

bash

awk 'function square(x) {return x*x} {print $1, square($2)}' data.txt

Module 7: Regular Expressions

1. Basic Patterns

bash

awk '/^a/ {print $0}' file.txt

Matches lines starting with `a`.


2. Advanced Patterns

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/8
bash

awk '/[0-9]+/ {print $0}' file.txt

Matches lines containing numbers.

Module 8: Processing Multiple Files

1. Read Two Files

bash

awk 'FNR==NR {a[$1]=$2; next} {print $1, a[$1], $2}' file1 file2

2. Merge Files

bash

awk 'NR==FNR {a[$1]=$2; next} $1 in a {print $0, a[$1]}' file1 file2

Module 9: Advanced Techniques

1. Working with Delimiters

bash

awk 'BEGIN {FS=","; OFS="|"} {print $1, $2}' file.csv

2. Extract and Analyze Data

bash

awk '{arr[$1]++;} END {for (i in arr) print i, arr[i]}' file.txt

3. Process Command Output

bash

ls -l | awk '{print $9, $5}'

Module 10: Debugging and Optimization

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/8
1. Debugging Mode

bash

awk -d script.awk

2. Optimizing Performance
Reduce unnecessary operations.
Use proper regex patterns.

Module 11: Practical Projects

1. Log File Analysis

bash

awk '/error/ {print $0}' /var/log/syslog

2. Data Transformation

bash

awk '{print $2, $1}' file.txt > output.txt

3. Dynamic Reports

bash

awk '{sum+=$2} END {print "Total:", sum}' sales.csv

Would you like to focus on any specific module or project?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/8

You might also like