AWS
re: Start
CHALLENGE LAB
Advanced Bash
Shell Scripting
>_
Overview
Shell scripting empowers users on Unix-based systems to
automate tasks. Scripts can manipulate files and directories,
process text efficiently, and even manage system
administration tasks. For anyone working with Unix systems,
mastering shell scripting unlocks a world of automation,
efficiency, and streamlined workflows.
Your Challenge
Write a Bash script based on the following requirements:
▪ Creates 25 empty (0 KB) files.
▪ The file names should be <yourName><number>,
<yourName><number+1>, <yourName><number+2>, and
so on.
▪ Design the script so that each time you run it, it creates the
next batch of 25 files with increasing numbers starting with
the last or maximum number that already exists.
▪ Do not hard code these numbers. You need to generate
them by using automation.
▪ Test the script. Display a long list of the directory and its
contents to validate that the script created the expected
files.
Note: This lab was made using Windows Subsystem for Linux.
Task 1
Use SSH to connect to an
Amazon Linux EC2
instance
Initial Preparations
In the AWS Management Console, select the EC2 instance and
make note of the Public IPv4 address.
Download the private key file [Link]. Change to the
Downloads directory and modify the permissions on the key to
be read-only (r--------).
Connect to the instance using SSH
Establish a connection to the EC2 instance using the ssh
command, the key and the instance’s public IPv4 address.
Task 2
Your Challenge
Adding the shebang line
#!/bin/bash
This line at the beginning of the script is called the shebang
line. It tells the system which interpreter to use to execute the
script. In this case, #!/bin/bash specifies that the script should
be run using the Bash shell.
Assigning the variable name
yourName="CristhianBecerra"
This line simply assigns the value "CristhianBecerra“, my name,
to the variable yourName, which is used later in the script to
construct the file names.
Task 2
Your Challenge
Finding the maximum number in existing files
maxNum=$(ls -1 | grep -oP “${yourName}\K\d+" | sort -n | tail -n1)
• ls -1: Lists the files in the directory one per line.
• grep -oP "${yourName}\K\d+": Uses grep to search for
the specified name followed by digits (\d+) using a regular
expression (-oP). The -o option displays only the part that
matches the regular expression. The P option enables grep
to use Perl-compatible regular expressions for advanced
pattern matching.
• \K: In the regular expression, \K means "forget what has
been matched before." In this case, it forgets the name and
only shows the following digits (\d+).
• sort -n: Sorts the found numbers numerically (-n) instead
of alphabetically.
• tail –n1: Takes the last line, which will be the highest
number found in the existing file names.
Task 2
Your Challenge
Setting the initial number for new files
if [ -z “$maxNum" ]; then
startNum=1
else
startNum= $((maxNum + 1))
fi
The -z condition checks if the string $maxNum is empty. In
this context, $maxNum would be empty if no files were found
with the name "CristhianBecerra," which means startNum is set
to 1. Otherwise, if existing files were found, startNum is set to
the highest number found plus one.
Creating 25 empty files with incremental names
for i in {0..24}; do
touch "${yourName}$((startNum + i))"
done
This for loop iterates 25 times. In each iteration, touch is used
to create a file with the constructed name by concatenating
name and the current number (startNum + i).
Task 2
Your Challenge
Typing the script
Type the script using the Vim text editor. Be sure to include
comments using # to enhance the readability of your code.
After saving your changes and closing the editor, change the
file permissions to make it executable.
Task 2
Your Challenge
Testing the script
Test the script. Display a long list of the directory and its
contents to validate that the script created the expected files.
Task 3
Add something extra!
Validating user input
echo –n "Please enter your name. Use only letters and underscores: "
read yourName
if [[ ! $yourName =~ ^[a-zA-Z_]+$ ]]; then
echo "Usage: The name should only contain letters or underscores."
exit 1
fi
• echo –n "Please enter your name. Use only letters and
underscores:": Prompts the user to input a name.
• read yourName: Reads user input and stores it in the
variable yourName.
• if [[ ! $yourName =~ ^[a-zA-Z_]+$ ]]; then: Checks if
the input contains only letters (uppercase or lowercase) or
underscores.
• echo "Usage: The name should only contain letters or
underscores.": Displays an error message if the input
contains invalid characters.
• exit 1: Exits the script with an error code of 1 if an invalid
input is detected.
Task 3
Add something extra!
Implementing proposed script updates
In the Vim text editor, update the script by replacing the existing
line yourName="CristhianBecerra" with the proposed modifications
to prompt the user for their name and validate the input.
Testing the input validation feature
Delete any previously generated empty files, then proceed to
test the new input validation feature of the updated script.
Conclusions
Bash scripting
Bash scripting is a versatile tool that automates tasks in Unix
systems, enhancing efficiency in system management and
development workflows.
Regular expressions
Regular expressions are powerful patterns used for text
manipulation, including tasks like pattern matching, data
validation, and text extraction.
The if statement
The if-else-fi construct in Bash facilitates conditional
execution, enabling scripts to make decisions based on specific
conditions and enhancing their decision-making capabilities.
The for loop
The for loop in Bash simplifies repetitive tasks by iterating over
values or items, streamlining processes like file handling,
command execution, and data processing within scripts.
Testing scripts
Testing scripts is essential to ensure their functionality,
reliability, and compatibility across different scenarios and
environments, including input validation, error handling, and
output verification.
Cristhian Becerra
cristhian-becerra-espinoza
+51 951 634 354
cristhianbecerra99@[Link]
Lima, Peru