JTCyberTech / Cybersecurity-Home-Labs

3 stars 1 forks source link

4. 25 Intermediate Bash Scripting Hands-On tasks #80

Open JTCyberTech opened 8 months ago

JTCyberTech commented 8 months ago

25 Intermediate Bash Scripting Hands-On tasks

Please use Task 1 as a refers for all description. Since there are a lot of overlapping scripts, I will only write description that are new.

Task 1:

Write a script that will ask user to input directory path and script will count total number of files in the given directory.

Command used:

Inside task1.sh Vim Editor:

Outside task1.sh Vim Editor:

Description:

Once clicked "Enter", you will be in Vim editor. Press "I" to convert to insert mode.

Inside Vim Editor:

Press "ESC" and type: :wq. Then, "Enter" to exit Vim Editor.



Task 2:

Write a script that will return the 10 largest directories and file (in terms of size) in the "/var/log" directory. Command used: - ```vi task2.sh``` Inside task2.sh Vim Editor: - ```#!/bin/bash``` - ```du -a /var/log | sort -n -r | head -n 10``` Outside task2.sh Vim Editor: - ```chmod 755 task2.sh``` - ```./task2.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```du -a /var/log | sort -n -r | head -n 10```: - ```du -a /var/log```: this command uses the du (disk usage) command to calculate the disk usage of files and directories within the "/var/log" directory. - ```-a```: option means that it will list individual files and directories, including all subdirectories. - ```|```: this is a pipe symbol, which takes the output of the previous command "du" and passes it as input to the next command "sort". - ```sort -n -r```: the sort command is used to sort the output from "du". - ```-n```: this option specifies numeric sorting, which ensures that the sizes are sorted as numbers rather than as strings. - ```-r```: this option means to sort in reverse order, putting the largest disk usage values at the top of the list. - ```|```: another pipe symbol takes the output of the sorted list and passes it to the head command. - ```head -n 10```: head command is used to display the first 10 lines (in this case, the top 10 disk usage entries) of its input.



Task 3:

Write a script that will keep writing user inputs from terminal into a file , until we press CTRL + D to save the changes. Command used: - ```vi task3.sh``` Inside task3.sh Vim Editor: - ```#!/bin/bash``` - ```echo "Enter text (Ctrl+D to save and exit):"``` - ```while read -r line; do``` - ```echo "$line" >> user_input.txt``` - ```done``` Outside task3.sh Vim Editor: - ```chmod 755 task3.sh``` - ```./task3.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo "Enter text (Ctrl+D to save and exit):"```: this line uses the echo command to display the message "Enter text (Ctrl+D to save and exit)" on the terminal. - ```while read -r line; do```: this line initiates a while loop. Here's what each part does: - ```while```: keyword that marks the beginning of the loop. - ```read -r line```: the read command is used to read user input from the terminal. The -r option is used for raw input, which prevents backslashes from being treated as escape characters. - ```;```: the ; (semicolon) is used to separate commands or statements in Bash. - ```do```: keyword marks the beginning of the loop's body. - ```echo "$line" >> user_input.txt```: inside the loop, this line uses the echo command to print the content of the line variable (the user's input) to the file named "user_input.txt." - ```>>```: operator is used to append the input to the end of the file. - ```done```: closing keyword for the loop, indicating the end of the loop's body.



Task 4:

Write a script that will capture the current date and then prints "Less than 10" if current date is less than 10 or prints "Equals to 10" if current date is equal to 10 else prints "Greater than 10" if current date is greater than 10. Command used: - ```vi task4.sh``` Inside task4.sh Vim Editor: - ```#!/bin/bash``` - ```currentdate=$(date +"%d")``` - ```if [ "$currentdate" -lt 10 ]; then``` - ```echo "Less than 10"``` - ```elif [ "$currentdate" -eq 10 ]; then``` - ```echo "Equals to 10"``` - ```else``` - ```echo "Greater than 10"``` - ```fi``` Outside task4.sh Vim Editor: - ```chmod 755 task4.sh``` - ```./task4.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```currentdate=$(date +"%d")```: this line assigns the value of the day of the month to a variable named "currentdate". Here's what each part does: - ```currentdate```: this is the variable that will store the day of the month. - ```=```: this is the assignment operator, used to assign a value to a variable. - ```$(date +"%d")```: this is a command substitution. It runs the "date" command with the format specifier "+"%d"" to get the day of the month, and the result is assigned to the "currentdate "variable. - ```if [ "$currentdate" -lt 10 ]; then```: this line starts an if statement, which is used to perform conditional checks. Here's what each part does: - ```if```: this is the keyword that marks the beginning of the conditional statement. - ```[ "$currentdate" -lt 10 ]```: this is the condition being checked. It checks if the value of the "currentdate" variable is less than 10. - ```-lt 10```: the -lt operator is used for numeric comparison, check value "less than 10". - ```then```: keyword marks the beginning of the code block that will be executed if the condition is true. - ```echo "Less than 10"```: If the condition is true, this line uses the "echo" command to print the message "Less than 10" to the terminal. - ```elif [ "$currentdate" -eq 10 ]; then```: this is an "else if" statement, which is used to specify an additional condition to check if the first condition is false. Here's what each part does: - ```elif```: this is the keyword used to specify an additional condition to check. - ```[ "$currentdate" -eq 10 ]```: this is the new condition being checked. It checks if the value of the "currentdate" variable is equal to 10. - ```-eq 10```: the -eq operator is used for numeric comparison. Check value "equal to 10". - ```then```: keyword marks the beginning of the code block that will be executed if the condition is true. - ```echo "Equals to 10"```: tf this condition is true, this line uses the "echo" command to print the message "Equals to 10" to the terminal. - ```else```: this is the keyword used to specify the code block that will be executed if none of the previous conditions is true. - ```echo "Greater than 10"```: if none of the previous conditions are true, this line uses the "echo" command to print the message "Greater than 10" to the terminal. - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement.



Task 5:

Write a script in which we must a function named as sum, which will be triggered to calculate the sum of 2 numbers provided by user at runtime. Command used: - ```vi task5.sh``` Inside task5.sh Vim Editor: - ```#!/bin/bash``` - ```sum() {``` - ```echo -n "Enter your first number: "``` - ```read num1``` - ```echo -n "Enter your second number: "``` - ```read num2``` - ```echo "Sum: $(( num1+num2 ))"``` - ```}``` - ```sum``` Outside task5.sh Vim Editor: - ```chmod 755 task5.sh``` - ```./task5.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```sum() {```: this line defines a Bash function named "sum." Functions in Bash are defined with 'function_name()' { syntax. - ```echo -n "Enter your first number: "```: This line uses the echo command to display the message "Enter your first number: " on the terminal. - ```-n```: option is used to prevent the addition of a newline character, which allows the user to enter input on the same line as the message. - ```read num1```: this line uses the "read" command to capture the user's input, which is expected to be the first number, and stores it in a variable named "num1". - ```echo -n "Enter your second number: "```: this line displays the message "Enter your second number: " in a similar fashion to the first message. - ```-n```: option is used to prevent the addition of a newline character, which allows the user to enter input on the same line as the message. - ```read num2```: this line uses the "read" command to capture the user's input, which is expected to be the second number, and stores it in a variable named "num2". - ```echo "Sum: $(( num1+num2 ))"```: this line calculates the sum of the values stored in num1 and num2, and then uses echo to display the result in the format "Sum: [result]." - ```}```: this is the closing curly brace that marks the end of the "sum" function. - ```sum```: this line calls the "sum" function, which triggers the function's logic, including prompting the user for two numbers and calculating their sum.



Task 6:

Write a script that will generate a factorial of a given number by the user as input. Command used: - ```vi task6.sh``` Inside task6.sh Vim Editor: - ```#!/bin/bash``` - ```echo -n "Enter your number: "``` - ```read num``` - ```factorial=1``` - ```while [ $num -gt 1 ]; do``` - ```factorial=$((factorial*num))``` - ```num=$((num-1))``` - ```done``` - ```echo "Factorial: $factorial"``` Outside task6.sh Vim Editor: - ```chmod 755 task6.sh``` - ```./task6.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo -n "Enter your number: "```: this line uses the echo command to display the message "Enter your number: " on the terminal. - ```-n```: option is used to prevent the addition of a newline character, which allows the user to enter input on the same line as the message. - ```read num```: this line uses the "read" command to capture the user's input, which is expected to be a number, and stores it in a variable named "num". - ```factorial=1```: this line initializes the factorial variable to 1. This variable will be used to calculate the factorial of the entered number. - ```while [ $num -gt 1 ]; do```: this line starts a while loop, which will continue as long as the value of num is greater than 1. - ```factorial=$((factorial*num))```: inside the loop, this line calculates the "factorial". It multiplies the current value of factorial by the current value of "num" and updates the "factorial" variable. - ```done```: closing keyword for the loop, indicating the end of the loop's body. - ```echo "Factorial: $factorial"```: after the loop, this line displays the result of the factorial calculation, including the message "Factorial: " followed by the value of the factorial variable.



Task 7:

Write a script that will check if you are currently logged in as root user or not. Command used: - ```vi task7.sh``` Inside task7.sh Vim Editor: - ```#!/bin/bash``` - ```if [ "$(id -u)" -eq 0 ]; then``` - ```echo "You are logged in as the root user."``` - ```else``` - ```echo "You are not logged in as the root user."``` - ```fi``` Outside task7.sh Vim Editor: - ```chmod 755 task7.sh``` - ```./task7.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```if [ "$(id -u)" -eq 0 ]; then```: this line starts an if statement, which is used to perform conditional checks. Here's what each part does: - ```if```: this is the keyword that marks the beginning of the conditional statement. - ```[ "$(id -u)" -eq 0 ]```: this is the condition being checked. It checks the result of the id -u command, which retrieves the user's UID (User ID), and compares it to 0. If the UID is 0, it indicates that the user is the root user. - ```then```: keyword marks the beginning of the code block that will be executed if the condition is true. - ```echo "You are logged in as the root user."```: if the condition is true (i.e., the UID is 0), this line uses the "echo" command to print the message "You are logged in as the root user." - ```else```: this is the keyword used to specify the code block that will be executed if the condition is false. - ```echo "You are not logged in as the root user."```: if the condition is false (i.e., the UID is not 0), this line uses the echo command to print the message "You are not logged in as the root user." - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement.



Task 8:

Write a script that will have a function named as "area" that will take two parameters within the script to calculate the area of rectangle. Command used: - ```vi task8.sh``` Inside task8.sh Vim Editor: - ```#!/bin/bash``` - ```area() {``` - ```local length=$1``` - ```local width=$2``` - ```local result=$((length * width))``` - ```echo "Area of the rectangle: $result square units."``` - ```}``` - ```echo -n "Enter the length of the rectangle: "``` - ```read length``` - ```echo -n "Enter the width of the rectangle: "``` - ```read width``` - ```area "$length" "$width"``` Outside task8.sh Vim Editor: - ```chmod 755 task8.sh``` - ```./task8.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```area() {```: this line defines a Bash function named "area." - ```local length=$1```: these line declare a local variables within the "area" function, "length", and assign it the values of the function's parameters "$1". This parameters represent the length of the rectangle provided when the function is called. - ```local width=$2```: these line declare a local variables within the "area" function, "width", and assign it the values of the function's parameters "$2". This parameters represent the width of the rectangle provided when the function is called. - ```local result=$((length * width))```: this line calculates the area of the rectangle by multiplying the length and width variables and assigns the result to a new variable named "result". - ```echo "Area of the rectangle: $result square units."```: this line uses the "echo" command to display a message that includes the calculated area in square units. - ```}```: this is the closing curly brace for the "area" function, marking the end of the function's code block. - ```echo -n "Enter the length of the rectangle: "```: is line displays a prompt for the user to enter the length of the rectangle. - ```-n```: option is used to prevent the addition of a newline character, allowing the input to be provided on the same line. - ```read length```: this line reads the user's input and assigns it to the "length" variable. - ```echo -n "Enter the width of the rectangle: "```: is line displays a prompt for the user to enter the width of the rectangle. - ```-n```: option is used to prevent the addition of a newline character, allowing the input to be provided on the same line. - ```read width```: this line reads the user's input and assigns it to the "width" variable. - ```area "$length" "$width"```: this line calls the "area" function, passing the user-provided values of 'length' and 'width' as arguments to the function.



Task 9:

Write a script which will print substring "like bash" from the given string "I like bash scripting". Command used: - ```vi task9.sh``` Inside task9.sh Vim Editor: - ```#!/bin/bash``` - ```input_string="I like bash scripting"``` - ```substring=$(echo "$input_string" | grep -o "like bash")``` - ```echo "$substring"``` Outside task9.sh Vim Editor: - ```chmod 755 task9.sh``` - ```./task9.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```input_string="I like bash scripting"```: this line defines a variable named input_string and assigns it the value "I like bash scripting," which is the input string from which you want to extract a substring. - ```substring=$(echo "$input_string" | grep -o "like bash")```: this line extracts the desired substring "like bash" from the input_string using the following steps: - ```echo "$input_string"```: this command prints the input_string to the standard output. - ```|```: this is the pipe operator, which redirects the output of the echo command to the input of the next command, which is grep. - ```grep -o "like bash"```: this command searches for the text "like bash" in the input (piped from the echo command) and uses the -o option to only print the matched part. - ```echo "$substring"```: this line prints the extracted substring stored in the substring variable, which should be "like bash" from the input string.



Task 10:

Write a script which will grep "error" in all the "*.log" files at /var/log directory, you need to print the unique file names which are having "error" string in them and remove duplicate file names from output. Command used: - ```vi task10.sh``` Inside task10.sh Vim Editor: - ```#!/bin/bash``` - ```grep -R --exclude-dir=dir "error" /var/log/*.log | awk -F: '{print $1}' | sort | uniq``` Outside task10.sh Vim Editor: - ```chmod 755 task10.sh``` - ```./task10.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```grep -R --exclude-dir=dir "error" /var/log/*.log | awk -F: '{print $1}' | sort | uniq```: - ```grep -R --exclude-dir=dir "error" /var/log/*.log```: this command uses grep to search for the string "error" recursively (-R) in all files with the ".log" extension within the "/var/log" directory. The --exclude-dir=dir option excludes the "dir" directory from the search. - ```grep```: this is the command used for searching text patterns in files. - ```-R```: this option tells 'grep' to perform a recursive search. It will search for the "error" string in all files within the specified directory and its subdirectories. - ```--exclude-dir=dir```: this option excludes the "dir" directory from the search. It ensures that files in the "dir" directory are not searched for "error." - ```"error"```: this is the text pattern you want to search for, in this case, the word "error." - ```/var/log/*.log```: this specifies the directory and the pattern for file names. It tells 'grep' to search for "error" in all files with the ".log" extension within the "/var/log" directory. - ```| awk -F: '{print $1}```: the pipe (|) operator redirects the output of the previous grep command to the awk command. - ```|```: This is the pipe operator, which redirects the output of the 'grep' command to the input of the 'awk' command. - ```awk -F: '{print $1}'```: this command uses the awk tool to process the output of grep. - ```-F```: it uses -F: to set the field separator as a colon (:). Then, it prints the first field, which is the file name that contains the "error" string. - ```| sort```: the pipe operator sends the output from 'awk' to the 'sort' command, which sorts the file names in alphabetical order. - ```| uniq```: the pipe operator sends the sorted list of file names to the uniq command, which removes duplicate lines, ensuring that each file name is listed only once.



Task 11:

Write a script which will grep "error" in all the "*.log" files at /var/log directory, you need to print the unique file names which are not having "error" string in them and remove duplicate file names from output. Command used: - ```vi task11.sh``` Inside task11.sh Vim Editor: - ```#!/bin/bash``` - ```grep -v -R --exclude-dir=dir "error" /var/log/*.log | awk -F: '{print $1}' | sort | uniq``` Outside task11.sh Vim Editor: - ```chmod 755 task11.sh``` - ```./task11.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```grep -v -R --exclude-dir=dir "error" /var/log/*.log | awk -F: '{print $1}' | sort | uniq```: - ```grep -R --exclude-dir=dir "error" /var/log/*.log```: this command uses the grep command to search for lines in all files with the ".log" extension within the "/var/log" directory. Here's what each part of the command does: - ```grep```: this is the command used for searching text patterns in files. - ```-v```: this option tells grep to invert the match, meaning it will display lines that do not contain the specified string, in this case, "error." - ```-R```: this option tells 'grep' to perform a recursive search. It will search for the "error" string in all files within the specified directory and its subdirectories. - ```--exclude-dir=dir```: this option excludes the "dir" directory from the search. It ensures that files in the "dir" directory are not searched for "error." - ```"error"```: this is the text pattern you want to search for, in this case, the word "error." - ```/var/log/*.log```: this specifies the directory and the pattern for file names. It tells 'grep' to search for "error" in all files with the ".log" extension within the "/var/log" directory. - ```| awk -F: '{print $1}```: the pipe (|) operator redirects the output of the previous grep command to the awk command. - ```|```: This is the pipe operator, which redirects the output of the 'grep' command to the input of the 'awk' command. - ```awk -F: '{print $1}'```: this command uses the awk tool to process the output of grep. - ```-F```: it uses -F: to set the field separator as a colon (:). Then, it prints the first field, which is the file name that contains the "error" string. - ```| sort```: the pipe operator sends the output from 'awk' to the 'sort' command, which sorts the file names in alphabetical order. - ```| uniq```: the pipe operator sends the sorted list of file names to the uniq command, which removes duplicate lines, ensuring that each file name is listed only once.



Task 12:

Write a script which will grep "error" or "host" keywords in all the "*.log" files at /var/log directory, you need to print all the errors on screen which are having both keywords in same row. Command used: - ```vi task12.sh``` Inside task12.sh Vim Editor: - ```#!/bin/bash``` - ```egrep "error|host" /var/log/*.log``` Outside task12.sh Vim Editor: - ```chmod 755 task12.sh``` - ```./task12.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```egrep "error|host" /var/log/*.log```: this command uses the egrep (extended grep) command to search for lines that contain either "error" or "host" in all "*.log" files within the "/var/log" directory. Here's what each part of the command does: - ```egrep```: this is the extended grep command, which allows you to use regular expressions and the | (pipe) symbol to specify multiple search patterns. - ```error|host```: this is the regular expression pattern. It searches for lines that contain either "error" or "host." - ```/var/log/*.log```: this specifies the directory to search ("/var/log") and the pattern of files to search for (files with the ".log" extension).



Task 13:

Write a script which will grep "error" in all the "*.log" files at /var/log directory, you need to make a copy of all the log files having "error" keyword in them and place the copy file at your current directory. Command used: - ```vi task13.sh``` Inside task13.sh Vim Editor: - ```#!/bin/bash``` - ```grep -R --exclude-dir=dir "error" /var/log/*.log | awk -F: '{print $1}' | sort | uniq | awk -F/ '{print $4}' | ``` - ```while read line ; do``` - ```cp /var/log/$line $line``` - ```done``` Outside task13.sh Vim Editor: - ```chmod 755 task13.sh``` - ```./task13.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```grep -R --exclude-dir=dir "error" /var/log/*.log```: this command uses the grep command to search for the string "error" in all "*.log" files within the "/var/log" directory. Here's what each part of the command does: - ```grep```: this is the command used to search for text in files. - ```-R```: this option tells 'grep' to search for the string "error" recursively in subdirectories. - ```--exclude-dir=dir```: this option excludes the "dir" directory from the search. If you want to exclude a specific directory, you can replace "dir" with the directory name you want to exclude. - ```"error"```: this is the search string, which is "error" in this case. - ```/var/log/*.log```: this specifies the directory to search ("/var/log") and the pattern of files to search for (files with the ".log" extension). - ```| awk -F: '{print $1}'```: the pipe (|) operator redirects the output of the previous grep command to the awk command. awk is used to process the output. This command extracts the first part of each line, which is the file name. - ```-F:```: option specifies that the field separator is a colon. - ```| sort | uniq```: the pipe operator sends the output from awk to the sort command, which sorts the file names in alphabetical order. Then it sends the sorted list of file names to the uniq command, which removes duplicate lines, ensuring that each file name is listed only once. - ```| awk -F/ '{print $4}'```: The pipe operator sends the output from uniq to another awk command. This command extracts the fourth part of each line, which is the file name without the full path. - ```-F/```: option specifies the field separator as a forward slash. - ```| while read line ; do ```: This part of the command uses the pipe operator (|) to take the output of the previous commands (a list of file names) and processes each file name one by one using a while loop. Here's what it does: - ```while read line```: this initiates a while loop that reads each line (file name) from the standard input and assigns it to the variable line. The loop continues as long as there are lines to read. - ```do```: keyword marks the beginning of the loop's body. - ```cp /var/log/$line $line```: inside the while loop, this command is executed for each file name obtained from the list. Here's what it does: - ```cp```: this is the copy command used to copy files. - ```/var/log/$line```: this represents the source file path. It appends the directory "/var/log/" to the file name obtained from the list ($line), specifying the source file to be copied. - ```$line```: this represents the destination file name. It specifies the name of the destination file in the current directory, which is the same as the file name obtained from the list. - ```done```: closing keyword for the loop, indicating the end of the loop's body.



Task 14:

Write a script to copy all .log files from /var/log to /tmp direcory. Once all files copied to /tmp directory, replace all the "error" keyword with "Warning" keyword in all .log files at /tmp directory. Command used: - ```vi task14.sh``` Inside task14.sh Vim Editor: - ```#!/bin/bash``` - ```cp /var/log/*.log /tmp/``` - ```ls /tmp/*.log | while read line ; do``` - ```sed -i 's/error/Warning/g' $line``` - ```done``` Outside task14.sh Vim Editor: - ```chmod 755 task14.sh``` - ```./task14.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```cp /var/log/*.log /tmp/```: this command uses the cp command to copy all "*.log" files from the "/var/log/" directory to the "/tmp/" directory. - ```ls /tmp/*.log | while read line ; do```: - ```ls /tmp/*.log```: this command uses ls to list all "*.log" files in the "/tmp/" directory. - ```|```: the pipe operator redirects the list of files from the ls command to the while loop. - ```while read line ; do```: this initiates a while loop that reads each file name (line) from the list and assigns it to the variable line. The loop continues as long as there are files to read. - ```sed -i 's/error/Warning/g' $line```: inside the while loop, this command is executed for each file name obtained from the list. Here's what it does: - ```sed```: this is the stream editor command. - ```-i```: this option tells sed to edit the files in place. - ```'s/error/Warning/g'```: this is a sed command that replaces all occurrences of "error" with "Warning" in the file. - ```$line```: this specifies the file name that is being processed within the loop. - ```done```: closing keyword for the loop, indicating the end of the loop's body.



Task 15:

Write a script to copy all .log files from /var/log to /tmp directory. Once all files copied to /tmp directory, replace the first occurrence of "host" keyword with "Machine" keyword in all .log files (if host keyword is repeated multiple times within single row, then first host keyword will be replaced). Command used: - ```vi task15.sh``` Inside task15.sh Vim Editor: - ```#!/bin/bash``` - ```cp /var/log/*.log /tmp/``` - ```ls /tmp/*.log | while read line ; do``` - ```sed -i 's/host/Machine/1' $line``` - ```done``` Outside task15.sh Vim Editor: - ```chmod 755 task15.sh``` - ```./task15.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```cp /var/log/*.log /tmp/```: this command uses the cp command to copy all "*.log" files from the "/var/log/" directory to the "/tmp/" directory. - ```ls /tmp/*.log | while read line ; do```: - ```ls /tmp/*.log```: this command uses ls to list all "*.log" files in the "/tmp/" directory. - ```|```: the pipe operator redirects the list of files from the ls command to the while loop. - ```while read line ; do```: this initiates a while loop that reads each file name (line) from the list and assigns it to the variable line. The loop continues as long as there are files to read. - ```sed -i 's/host/Machine/1' $line```: inside the while loop, this command is executed for each file name obtained from the list. Here's what it does: - ```sed```: this is the stream editor command. - ```-i```: this option tells sed to edit the files in place. - ```'s/host/Machine/1'```: this is a sed command that replaces the first occurrence of "host" with "Machine" in the file. - ```$line```: this specifies the file name that is being processed within the loop. - ```done```: closing keyword for the loop, indicating the end of the loop's body.



Task 16:

Write a script that will display 2 Columns (Mounted and Used%) , mount name and disk usage percentage in sorted order from low used % to high %. Command used: - ```vi task16.sh``` Inside task16.sh Vim Editor: - ```#!/bin/bash``` - ```df -k | awk '{print $6,$5}' | sort -k2 -n | grep -v Use%``` Outside task16.sh Vim Editor: - ```chmod 755 task16.sh``` - ```./task16.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```df -k | awk '{print $6,$5}' | sort -k2 -n | grep -v Use%```: - ```|```: the pipe (|) operator is used to send the output of the df -k command as input to the next command. - ```awk '{print $6,$5}'```: this awk command processes the output from the previous command and prints the 6th and 5th columns from the input (which are the mount point and usage percentage). - ```|```: another pipe operator is used to send the output of the awk command to the next command. - ```sort -k2 -n```: this sort command is used to sort the input based on the second column (-k2) numerically (-n), which is the usage percentage. - ```|```: another pipe operator is used to send the sorted output to the next command. - ```grep -v Use%```: this grep command searches for lines that do not contain the string "Use%" in the output. The -v option is used to invert the match and exclude lines containing "Use%."



Task 17:

Write a script that will sleep for 100 seconds, but when we trigger the script it must ran in the background mode. Command used: - ```vi task17.sh``` Inside task17.sh Vim Editor: - ```#!/bin/bash``` - ```sleep 100 &``` Outside task17.sh Vim Editor: - ```chmod 755 task17.sh``` - ```./task17.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```sleep 100 &```: - ```sleep 100```: te sleep 100 command is used to pause the script's execution for 100 seconds. - ```&```: & operator is added at the end to run the sleep command in the background, allowing the script to continue running and not block your terminal.



Task 18:

Write a script that will take 2 command line arguments (numbers) from user and then print the sum on screen. Command used: - ```vi task18.sh``` Inside task18.sh Vim Editor: - ```#!/bin/bash``` - ```echo $(($1 + $2))``` Outside task18.sh Vim Editor: - ```chmod 755 task18.sh``` - ```./task18.sh 10 20``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo $(($1 + $2))```: this line calculates the sum of the first and second command-line arguments, denoted as $1 and $2, respectively, and then echoes (prints) the result to the screen. - ```./task18.sh 10 20```: this is how you would run the script, passing the numbers 10 and 20 as command-line arguments. The script will calculate the sum and print it to the screen.



Task 19:

Write a script that will take 2 command line arguments (numbers) from user and then print the sum on screen, if user don’t input 2 numbers as argument, then display an error message. Command used: - ```vi task19.sh``` Inside task19.sh Vim Editor: - ```#!/bin/bash``` - ```if [ "$#" -ne 2 ]; then``` - ```echo "Error: Please provide exactly two numeric arguments."``` - ```exit 1``` - ```fi``` - ```echo $(($1 + $2))``` Outside task19.sh Vim Editor: - ```chmod 755 task19.sh``` - ```./task19.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```if [ "$#" -ne 2 ]; then```: this line checks if the number of command-line arguments ($#) is not equal to 2. In other words, it verifies that the user has provided exactly two command-line arguments. - ```echo "Error: Please provide exactly two numeric arguments."```: If the condition in the 'if' statement is true (i.e., not exactly two arguments were provided), this line prints an error message to the screen. - ```exit 1```: after displaying the error message, the script exits with an exit status of 1, indicating that an error occurred. - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement. - ```echo $(($1 + $2))```: If the condition in the 'if' statement is false (i.e., exactly two arguments were provided), this line calculates the sum of the first ($1) and second ($2) command-line arguments and then echoes (prints) the result to the screen.



Task 20:

Write a script that will allow the user choose a color and shows a comment against that color (using case statement). Command used: - ```vi task20.sh``` Inside task20.sh Vim Editor: - ```#!/bin/bash``` - ```echo "Choose a color:"``` - ```echo "1 - Red"``` - ```echo "2 - Green"``` - ```echo "3 - Blue"``` - ```echo "4 - Purple"``` - ```read color``` - ```case "$color" in``` - ```1) echo "Red is selected";;``` - ```2) echo "Green is selected";;``` - ```3) echo "Blue is selected";;``` - ```4) echo "Purple is selected";;``` - ```*) echo "Please choose a number from the menu.";;``` - ```esac``` Outside task20.sh Vim Editor: - ```chmod 755 task20.sh``` - ```./task20.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo "Choose a color:"``` - ```echo "1 - Red"``` - ```echo "2 - Green"``` - ```echo "3 - Blue"``` - ```echo "4 - Purple"``` - These lines display a menu of color choices to the user. The user is prompted to enter a number corresponding to their color choice. - ```read color```: this line reads the user's input (the chosen number) and stores it in the color variable. - ```case "$color" in``` - ```1) echo "Red is selected";;``` - ```2) echo "Green is selected";;``` - ```3) echo "Blue is selected";;``` - ```4) echo "Purple is selected";;``` - ```*) echo "Please choose a number from the menu.";;``` - ```esac``` - The case statement is used to process the value of color. Depending on the value, the script prints a message associated with the chosen color. If the user enters an invalid choice (a number other than 1, 2, 3, or 4), the script displays a message to choose a number from the menu.



Task 21:

Create a file named as "devops.txt" , then using vi editor insert 1..10 numbers like shown below.



then write a script to calculate sum of all numbers written inside devops.txt file. Creating file: - ```vi devpos.txt```



Command used: - ```vi task21.sh``` Inside task21.sh Vim Editor: - ```#!/bin/bash``` - ```awk '{x+=$0} END{print x}' devops.txt``` Outside task21.sh Vim Editor: - ```chmod 755 task21.sh``` - ```./task21.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```awk '{x+=$0} END{print x}' devops.txt```: - ```awk '{x+=$0}```: this part of the script uses the awk command to process the contents of a file, in this case, devops.txt. It calculates the sum of all the numeric values in the file. - ```{x+=$0}```: this part of the awk command accumulates the sum in a variable x. $0 refers to the entire line, and this line simply adds the numeric values in each line to x. - ```END{print x}'```: the END block in awk is executed after all lines in the file have been processed. It prints the value of x, which is the sum of all numeric values in the file. - ```devops.txt```: this is the name of the file that awk is processing to calculate the sum of its numeric values.



Task 22:

Write a script that will validate password strength. Here are few conditions that needs to be validated - Minimum length to be 10 characters - Must have both the Small and Upper case letters Command used: - ```vi task22.sh``` Inside task22.sh Vim Editor: - ```#!/bin/bash``` - ```echo "Enter your password:"``` - ```read password``` - ```if [ ${#password} -lt 10 ]; then``` - ```echo "Password is too short. It must be at least 10 characters long."``` - ```exit 1``` - ```fi``` - ```if ! [[ "$password" =~ [a-z] ]] || ! [[ "$password" =~ [A-Z] ]]; then``` - ```echo "Password must contain both lowercase and uppercase letters."``` - ```exit 1``` - ```fi``` - ```echo "Password is valid."``` Outside task22.sh Vim Editor: - ```chmod 755 task22.sh``` - ```./task22.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo "Enter your password:"``` - ```read password``` - These lines prompt the user to enter a password and then read the user's input, storing it in the password variable. - ```if [ ${#password} -lt 10 ]; then```: this line checks the length of the password using ${#password}. If the length is less than 10 characters, the condition in the if statement is true, and it proceeds with the following block of code. - ```echo "Password is too short. It must be at least 10 characters long."``` - ```exit 1``` - If the password length is less than 10 characters, this part of the script prints an error message and exits the script with an exit status of 1. - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement. - ```if ! [[ "$password" =~ [a-z] ]] || ! [[ "$password" =~ [A-Z] ]]; then```: This line uses regular expressions to check if the password contains both lowercase letters [a-z] and uppercase letters [A-Z]. If either condition is not met, the if statement is true, and the following block of code is executed. - ```echo "Password must contain both lowercase and uppercase letters."``` - ```exit 1``` - If the password doesn't contain both lowercase and uppercase letters, this part of the script prints an error message and exits with an exit status of 1. - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement. - ```echo "Password is valid."```: If the password meets both conditions (length >= 10 characters and contains both lowercase and uppercase letters), this part of the script prints "Password is valid."



Task 23:

Write a script that will display the last (recently) updated file or the latest file in the directory given by the user. Command used: - ```vi task23.sh``` Inside task23.sh Vim Editor: - ```#!/bin/bash``` - ```echo "Enter the directory path"``` - ```read a;``` - ```ls -lrt $a | grep ^- | awk 'END{print $NF}'``` Outside task23.sh Vim Editor: - ```chmod 755 task23.sh``` - ```./task23.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```echo "Enter the directory path""``` - ```read a;``` - These lines prompt the user to enter a directory path and then read the user's input, storing it in the variable 'a'. - ```ls -lrt $a```: this line lists the contents of the directory specified by the user, sorted by modification time in reverse order (newest files first). The result includes directories, files, and other types of entries. - ```| grep ^- | awk 'END{print $NF}'```: this part of the script uses a pipeline (|) to process the output of the ls command. - ```grep ^-```: this part filters the output to only include regular files (not directories or other types of entries). The ^- pattern matches lines that start with a hyphen, which is the character used to denote regular files in the ls -lrt output. - ```awk 'END{print $NF}'```: this part uses awk to print the last field ($NF) of the final line (END) of the filtered output. In this context, the last field corresponds to the name of the newest regular file in the directory.



Task 24:

Write a script that will print a number in reverse order. Script will take input number as argument and if argument is missing then it must through an error to provide the number in the argument. Command used: - ```vi task24.sh``` Inside task24.sh Vim Editor: - ```#!/bin/bash``` - ```if [ $# -ne 1 ]; then``` - ```echo "Please input the number as an argument that you want to reverse"``` - ```exit 1``` - ```fi``` - ```a=$1``` - ```rev=0``` - ```while [ $a -gt 0 ]; do``` - ```b=$(($a % 10))``` - ```rev=$(($rev * 10 + $b))``` - ```a=$(($a / 10))``` - ```done``` - ```echo "Reverse number : $rev"``` Outside task24.sh Vim Editor: - ```chmod 755 task24.sh``` - ```./task24.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```if [ $# -ne 1 ]; then```: this line checks if the number of command-line arguments is not equal to 1. If the condition is true, it proceeds with the following block of code. - ```echo "Please input the number as an argument that you want to reverse"``` - ```exit 1``` - if the condition is true (i.e., no or more than one argument is provided), this part of the script prints an error message and exits with an exit status of 1. - ```fi```: this fi marks the end of the if condition. - ```a=$1``` - ```rev=0``` - These lines initialize variables a and rev. a is assigned the value of the first command-line argument, and rev is initialized to 0. - ```while [ $a -gt 0 ]; do```: this line starts a while loop that continues as long as the value of a is greater than 0. - ```b=$(($a % 10))```: inside the loop, this line calculates the last digit of the number by taking the modulo (%) of a with 10 and assigns it to the variable b. - ```rev=$(($rev * 10 + $b))```: this line reverses the number by taking the current value of rev, multiplying it by 10 (shifts the digits left by one position), and adding the value of b. - ```a=$(($a / 10))```: this line removes the last digit from the number by performing integer division of a by 10, effectively shifting the digits right by one position. - ```done```: this done marks the end of the while loop. - ```echo "Reverse number : $rev"```: the script prints the reversed number, which is stored in the variable 'rev'.



Task 25:

Write a script that will create 2 directories named "odd" and "even", then write a for loop that will generate empty files in these 2 directories. If number is odd then file will be created in odd directory else inside even directory for eg: odd/1.txt, odd/3.txt , even/2.txt and so on till 20.txt. Command used: - ```vi task25.sh``` Inside task25.sh Vim Editor: - ```#!/bin/bash``` - ```mkdir odd``` - ```mkdir even``` - ```for (( n=1; n<=20; n++ )); do``` - ```if (( $n%2==0 )); then``` - ```touch even/$n.txt``` - ```else``` - ```touch odd/$n.txt``` - ```fi``` - ```done``` Outside task25.sh Vim Editor: - ```chmod 755 task25.sh``` - ```./task25.sh``` Description: - ```#!/bin/bash```: this is the shebang line, indicating that the script should be executed using the Bash shell. - ```mkdir odd``` - ```mkdir even``` - these lines create two directories named "odd" and "even" in the current working directory. These directories will be used to store text files. - ```for (( n=1; n<=20; n++ )); do```: this line starts a for loop that iterates from n=1 to n=20. - ```if (( $n%2==0 )); then```: inside the loop, this line checks if the current value of n is even by performing a modulo operation ($n % 2). If the result is equal to 0, it means that n is even. - ```touch even/$n.txt```: if n is even, this line creates an empty text file with a name in the format n.txt in the "even" directory. - ```else```: if n is not even (i.e., it's odd), the script proceeds to the else block. - ```touch odd/$n.txt```: in the else block, this line creates an empty text file with a name in the format n.txt in the "odd" directory. - ```fi```: this is the closing keyword for the "if" statement, indicating the end of the conditional statement. - ```done```: this done marks the end of the while loop.