Chapter 4: Linux Advanced Commands
Friends, basic commands help us navigate, read and manage files on the server. With advanced commands – searching logs, automating work, managing services, checking the network and disk – you do the daily work of a cloud engineer. In a real job nobody opens a 2 GB log file in nano; we use grep, awk and pipes. The example in this chapter stays the same: the EC2 web server of a dairy brand like Amul (sample data, for practice) – its logs, backups and services. Come on, let's learn to work like a pro.
मित्रांनो, बेसिक कमांड्सने आपण सर्व्हरवर फक्त फिरू शकतो. ॲडव्हान्स्ड कमांड्सने लॉग्स शोधणं, काम ऑटोमेट करणं, सर्व्हिसेस मॅनेज करणं, नेटवर्क आणि डिस्क चेक करणं – हे क्लाउड इंजिनिअरचं रोजचं काम. रिअल जॉबमध्ये 2 GB ची लॉग फाइल कोणी nano मध्ये उघडत नाही; आपण grep, awk आणि पाइप्स वापरतो. या चॅप्टरमध्ये उदाहरण तेच: Amul-style dairy (सॅम्पल डेटा, सरावासाठी) चा EC2 वेब सर्व्हर – त्याचे लॉग्स, बॅकअप्स आणि सर्व्हिसेस. चला, प्रो सारखं काम करायला शिकूया.
दोस्तों, बेसिक कमांड्स से हम सर्वर पर सिर्फ़ घूम सकते हैं. एडवांस्ड कमांड्स से लॉग्स ढूँढना, काम ऑटोमेट करना, सर्विसेस मैनेज करना, नेटवर्क और डिस्क चेक करना – ये क्लाउड इंजीनियर का रोज़ का काम है. रियल जॉब में 2 GB की लॉग फ़ाइल कोई nano में नहीं खोलता; हम grep, awk और पाइप्स इस्तेमाल करते हैं. इस चैप्टर में उदाहरण वही: Amul-style dairy (सैंपल डेटा, सिर्फ़ अभ्यास के लिए) का EC2 वेब सर्वर – उसके लॉग्स, बैकअप्स और सर्विसेस. चलो, प्रो की तरह काम करना सीखते हैं.
In this chapter
- Searching with grep and find
- Text processing: awk and sed
- Pipes, redirection, here-docs
- Archives: tar, gzip and zip
- Services, systemctl, journalctl
- Network and disk commands
- Scheduling jobs with cron
- Variables, ssh and scp
- Monitoring and shell scripts
Concepts in this chapter
- 4.1Searching text: grep
- 4.2Finding files: find
- 4.3Text processing: awk and sed
- 4.4Pipes and redirection
- 4.5Archiving and compression: tar, gzip, zip
- 4.6Services: service, systemctl and journalctl
- 4.7Networking commands
- 4.8Disk and storage commands
- 4.9Scheduling tasks: cron
- 4.10Environment variables
- 4.11Remote access: ssh and scp
- 4.12Monitoring: top and htop
- 4.13Basic shell scripting
Review and practice
Follow the workshop report through four stages
Read all steps
- Known input
Start with four measurements whose expected results you can calculate yourself. The sample contains two failures with pressures twelve and eight. A known input gives you an independent check.
- Select and calculate
Select the failed records, then total their pressure and count the selected rows. The expected count is two and the average is ten. Explain the data passed between stages.
- Reviewed output
Save the generated result under a distinct output path. Inspect the result and confirm that the original measurements remain unchanged. A successful command still needs a meaningful output check.
- Restore check
Archive the input and report together, extract into a fresh directory and compare recovered bytes. Creating an archive and demonstrating recovery are separate steps.
Turn workshop measurements into a useful report
Imagine an engineering workshop that tests small water pumps. Each test records a pump identifier, the pressure observed and whether the test passed. A Linux server stores the results and prepares a daily report for the instructor. Nobody expects the instructor to open hundreds of files and add every number manually. The server should find the right records, select the relevant rows, calculate the summary and save it where the instructor can read it. Advanced Linux commands provide small, understandable tools for these jobs.
The word advanced does not mean that every command is long or difficult. It means you begin combining responsibilities. One program searches text, another selects fields, and another writes an archive. A shell connects their input and output. A service manager supervises a long-running application. A scheduler starts a job at a chosen time. You can understand this arrangement without a computer-science background: describe the work in ordinary words, then choose a tool for each part.
Our workshop is an invented training scenario. Commands that create or change data in the main exercise work inside a new temporary directory. You need a Linux training environment with Bash and common command-line utilities. Some examples also work on macOS, but options and output can differ. The service, disk and network sections identify Linux tools. If a tool is missing, learn its role first and use an approved training machine for that part.
Keep three questions beside your terminal. Which machine am I using? Which input am I reading? Which output am I about to create or replace? A correct report command can still produce the wrong business result if it reads yesterday’s file. A correct copy operation can still put the report in the wrong directory. Knowing the syntax is only part of understanding an operation.
By the end of this chapter you should be able to explain a small reporting workflow from start to finish. Find the input, inspect the data, run the transformation, check its exit status, examine the result and preserve enough evidence to repeat the calculation. The individual lessons develop each tool further. This overview gives you a working picture of how they cooperate.
Create a known input before learning the tools
A useful lab begins with data whose correct answer you can calculate yourself. If a file contains millions of unfamiliar lines, an incorrect command may still produce a convincing number. Our first file has four measurement rows. Two tests pass, two fail, and the failed pressure values are twelve and eight. Their average is ten. These small facts provide an independent check on the commands.
Run this block in Bash. The temporary-directory command chooses a fresh path. The variable stores that path so later commands can name it exactly. The checks stop setup if the directory cannot be created or entered. Keep this terminal open while working through the connected exercise.
workshop_lab=$(mktemp -d) || exit 1
cd "$workshop_lab" || exit 1
mkdir inputs reports restored
printf '%s\n' 'pump,pressure,result' 'P101,14,PASS' 'P102,12,FAIL' 'P103,16,PASS' 'P104,8,FAIL' > inputs/pumps.csv
pwd
cat inputs/pumps.csv
The displayed path should be the new workspace. The file should contain a header followed by four rows. The comma separates fields in this deliberately simple dataset. Real CSV can contain quoted commas and line breaks inside fields; these small field-based examples do not parse every valid CSV file. For general CSV processing, use a parser that understands the format.
The single quotes keep each record literal. The output operator writes the printed records into the named file. Because the file is inside a newly created workspace, the exercise is not replacing an existing workshop report. Later, you will see why this distinction matters when redirection is used with important files.
Draw the workspace as a small tree. Put the measurement file under inputs and leave reports and restored empty. After each exercise, update the drawing. Distinguish a file that was read, a new file that was created and an existing file that was changed. The same reasoning applies to an application directory on EC2, even when it contains many more files.
Select matching lines with grep
Suppose the instructor asks to see failed tests. The required operation is to keep rows containing a particular result. The grep program searches text and prints matching lines. A pattern describes a match. Start with a fixed-string search, which treats supplied characters literally, before introducing patterns that give some characters special meanings.
grep -n -F 'FAIL' inputs/pumps.csv
You should see the P102 and P104 rows with their line numbers. Those numbers refer to lines in this file, including its header. They do not refer to pump identifiers or the number of failed tests. Line numbers help you return to surrounding input. Fixed-string matching is useful when a literal identifier contains punctuation that a regular expression could interpret differently.
Now make the condition precise. In this file, result is the final field. A pattern ending with a dollar sign matches the end of a line. A comma followed by FAIL at the end therefore excludes FAILURE. The precision matters when the question concerns a field value rather than the appearance of a word anywhere in a record.
grep ',FAIL$' inputs/pumps.csv
grep -c ',FAIL$' inputs/pumps.csv
The first command prints two records. The second prints two, the count of matching lines. Counting matching lines differs from counting every occurrence of a word. A line containing a word three times still contributes one matching line. Name the metric clearly: failed measurement rows, matching requests and occurrences are different quantities.
A command also returns an exit status. For grep, a search with at least one selected line normally returns zero, while no selected lines normally returns one. An error has a different status. A script must distinguish an empty result from an unreadable file. Read the question the command was asked and the meaning of its documented status before classifying the outcome.
Predict the result of searching for the absent identifier P999. Then search a deliberately nonexistent filename inside this workspace. The first experiment has valid input and no match. The second cannot read its input. The output and immediately captured exit status explain the difference. This prevents reporting that no errors occurred when a log was never read.
Find files by their properties
A text search assumes you know which file to read. Often you first need to discover that file. The find command walks a directory tree and evaluates conditions on each entry. The starting directory controls the search boundary. A name condition checks a filename, a type condition distinguishes regular files from directories, and other conditions inspect properties such as size or modification time.
find inputs -type f -name '*.csv' -print
The expected result is the measurement file. The quoted pattern reaches find unchanged. Without quotes, the shell may expand the asterisk using names in the current directory before find receives the argument. That changes the question. Two programs participate in this command line: the shell prepares arguments, then find interprets its options and expressions.
Keep the first search narrow. Looking under the workspace’s input directory is easier to understand than starting at the filesystem root. A root-wide search can cross unrelated directories, produce permission errors and hide the interesting result among thousands of paths. If a report job reads one application tree, begin there and widen the search when evidence calls for it.
Finding an entry and acting on it are separate stages. Print selected paths and inspect them before a copy, permission change or removal. A filename can contain spaces, so copying a printed list into an unquoted command is unreliable. For programmatic processing, use a filename-safe mechanism such as find’s execution facility or a correctly matched null-delimited pipeline. One visual word is not necessarily one filename.
Try creating a second input named pump notes.csv with a harmless note, then repeat the search. The space belongs to its name. Explain why the quoted name pattern finds it and why a later command must keep the complete path together. Remove only this extra practice file after inspecting it. This connects quoting to a practical search task.
Time-based searches need careful wording too. A modification time records a filesystem event, not necessarily the date of measurements inside a file. Copying, restoring or editing data can change that relationship. If the question asks for measurements from Monday, the condition may belong inside each record. Use file timestamps for questions about files and record timestamps for questions about their data.
Read fields and calculate with awk
The instructor wants a compact list of failed pump identifiers and pressures. Awk processes records, usually lines, and makes fields available to a small program. In this controlled file, a comma separates fields. The first field is the identifier, the second is pressure and the third is result. A condition selects a record, and an action decides what to print or calculate.
awk -F, 'NR > 1 && $3 == "FAIL" { print $1, $2 }' inputs/pumps.csv
The output should show P102 with twelve and P104 with eight. The record-number condition skips the header. The comparison selects records whose third field matches the chosen result. The print action selects two fields. Each part corresponds to an ordinary sentence: after the header, for failed records, print identifier and pressure. Read the command this way before memorizing punctuation.
To calculate an average, keep a running total and count. Each selected record contributes its pressure to the total and one to the count. At the end, divide only if the count exceeds zero. A file with no failures needs a clear result rather than division by zero. This is both a programming and a data-interpretation lesson.
awk -F, '
NR > 1 && $3 == "FAIL" { total += $2; count++ }
END {
if (count > 0)
printf "Failed tests: %d; average pressure: %.1f\n", count, total / count
else
print "No failed tests in this input"
}
' inputs/pumps.csv
Expect two failed tests and average pressure ten. Check against your handwritten calculation. A program can be syntactically correct while calculating the wrong population, such as all pumps instead of failed pumps. The independent answer catches that mistake. With larger data, use a representative sample and a clearly defined metric before trusting a report.
Field-based processing depends on an input contract. What happens if pressure is missing, includes a unit suffix or contains an unexpected word? A production program should validate such cases and report rejected rows. This fixture uses simple valid numbers so you can first learn selection and accumulation. Extending a program should make its assumptions explicit, rather than treating questionable input as a trustworthy measurement.
Tool choice follows format and complexity. A database may be the right place for a large relational query. Quoted CSV needs a suitable CSV reader. JSON needs a JSON-aware tool. Learning a command includes learning where its simple input model stops being appropriate.
Transform a copy before replacing an input
Sometimes data is correct but its presentation needs a change. Sed reads text through editing instructions and normally writes the result to standard output. A substitution replaces a matching portion of a line. Begin by displaying the transformation without changing its source. This gives you a preview and a straightforward comparison.
sed 's/,FAIL$/,REVIEW/' inputs/pumps.csv
The two failed result fields should appear as REVIEW in the displayed output. Passing rows and the header remain unchanged. The comma and end-of-line condition narrow the replacement to this simple final field. The input still contains FAIL because this command did not request an in-place edit. A generated result and a changed source are different outcomes.
Write an acceptable result to a separate report and inspect both versions. A distinct name makes its role obvious. The input is recorded measurement data; the output is a view prepared for review. Changing a label in a report should not quietly alter the original record of a failed test.
sed 's/,FAIL$/,REVIEW/' inputs/pumps.csv > reports/review.csv
cat reports/review.csv
grep -c ',FAIL$' inputs/pumps.csv
The last command should still count two failed input rows. It deliberately checks that the source was preserved. For a configuration change, also validate the new configuration with the application’s checker before making it active. Successful text replacement does not prove that the edited file is meaningful to its eventual reader.
Regular expressions can match more than intended. Replacing every occurrence of a short word may change comments, unrelated paths or parts of longer identifiers. Inspect the selected lines and use the narrowest suitable pattern. Structured files with nesting or escaping usually deserve a format-aware editor or parser instead of increasingly complicated substitutions.
In-place options differ across sed implementations. The beginner pattern here is explicit: read one file, write another, compare, then decide about replacement. This creates a natural place for review and rollback in a deployment workflow.
Connect programs through streams and exit statuses
A command can receive standard input and write standard output and standard error. These are separate communication channels. Standard output carries the requested result; standard error carries diagnostics. A pipe connects one command’s standard output to the next command’s standard input. It does not normally save an intermediate file or automatically include the first command’s error messages.
grep ',FAIL$' inputs/pumps.csv | awk -F, '{ print $1 }'
The first program selects failed rows. The second prints their identifiers. Expect P102 and P104. Describe the intermediate stream: complete comma-separated measurement lines, not merely the word FAIL. Knowing what crosses the connection helps you change a stage without losing track of what the next stage expects.
A single greater-than operator opens an output file for replacement. A doubled operator appends. If a daily report should contain only today’s result, appending every run may create repeated data. If an audit log should preserve previous entries, replacing it removes evidence. Choose based on the intended lifecycle of the file.
Do not redirect a transformation into the same file it is reading in the ordinary way. The shell can truncate the destination before the program reads its input. Use a separate output path, verify it and then decide how to replace the old file. A temporary output and a carefully performed rename are often part of reliable reporting, but the replacement behavior must fit the filesystem and application.
By default, Bash reports the exit status of the last pipeline command. An earlier stage can fail while a later stage successfully processes an empty stream. Bash’s pipefail option changes how a failing pipeline is reported, but it does not explain the failure or validate the result’s business meaning. Capture statuses and diagnostics where needed.
Run each stage separately against the small fixture, inspect its output, and then combine verified stages. An empty report could mean no matching records, missing input or a failed writer. These are different outcomes. A longer pipeline is not a substitute for understanding the current one.
Preserve a collection and prove it can be restored
The workshop wants to retain the input and reviewed output together. Archiving gathers files and their names into one container. Compression reduces the bytes representing that container or an individual file. Tar handles archives; gzip is a compression format and tool commonly combined with tar. The combined filename usually signals both operations, but a filename does not prove the contents are valid.
tar -czf workshop-bundle.tar.gz inputs reports
tar -tzf workshop-bundle.tar.gz
tar -xzf workshop-bundle.tar.gz -C restored
cmp inputs/pumps.csv restored/inputs/pumps.csv
Creation stores the two directories in a compressed archive. Listing displays its members without extraction. Extraction writes into the fresh restored directory. The comparison should produce no difference and return zero. It verifies that restored measurement bytes match the original. Repeat the comparison for the report file.
The archive is outside the directories being archived, avoiding inclusion of the archive while it is being written. Stored paths are relative to the workspace, making the restore structure understandable. For an archive received from elsewhere, inspect members before selecting an extraction destination. Restore into a fresh directory and review its contents before moving anything into an application tree.
An archive on the same disk is useful here but is not a complete disaster-recovery design. Losing that disk can remove both original and archive. Real backups need suitable separate storage, access control, retention and a tested recovery procedure. Copying an active database’s files arbitrarily may not provide a consistent database backup.
Record what was included, when it was captured and how it was restored. You should be able to explain which input produced the workshop report and reproduce its calculation from recovered files. That ability is more useful than archives whose contents and recovery procedures nobody has checked.
Separate a running service from its startup policy
A website or report receiver usually needs to keep running after an administrator closes the terminal. On many Linux distributions, systemd manages such services. A unit describes a managed resource; a service unit describes how a particular program is started and supervised. The unit name is an identifier used by the manager. It is not necessarily the same as the program’s executable filename.
Two service questions are often confused. Active concerns the present state. Enabled concerns installation into the relevant startup relationships. A service can be running now without being enabled for the intended startup target. It can also be enabled while presently stopped or failed. Some units have other activation arrangements, so read the actual unit rather than assuming every service follows one simple boot rule.
systemctl status workshop-report.service --no-pager
systemctl is-active workshop-report.service
systemctl is-enabled workshop-report.service
journalctl -u workshop-report.service -n 30 --no-pager
These are read-only examples for a training host where that named service exists. Our file-only exercise has not installed it. On your own system, substitute an existing service you are authorized to inspect. An unknown-unit message is expected if the example service was never created; it does not mean systemd itself is broken.
Read the status and journal together. The status provides a current summary; the journal can show earlier starts, exits and error messages. A running process is not proof that its application can complete every request. The reporting program might be alive but unable to read its input directory. Verify its actual output or health operation as well as its manager state.
Reloading the manager’s unit definitions is different from asking an application to reload its configuration. Restarting a service is different again because it stops and starts the managed work. Learn which component owns the changed file before selecting an operation. The main exercise does not need service changes; later service labs can explore them in a disposable environment.
Match each network observation to the question it answers
Suppose the workshop’s report page does not open from a student’s laptop. Linux provides several observations, each covering part of the path. Interface addresses describe the local network configuration. Routes describe the next-hop selection. Listening sockets show where programs wait for connections. An application request checks a particular protocol and resource. Combining these observations is useful because they do not all prove the same thing.
ip -brief address
ip route
ss -ltn
curl --connect-timeout 3 -i http://127.0.0.1:8000/
The last command is a local example only. It expects a test HTTP service already listening on port eight thousand. If none exists, a connection error is a legitimate observation. Do not launch an internet-facing service merely to make the example succeed. A loopback service can be used later to distinguish a listening process from a missing application path.
A successful local request tells you about the process reached on that local path. It does not prove that the AWS subnet, security group, load balancer or student’s network allows an outside request. Conversely, a successful ping checks an ICMP exchange, not whether the report application can serve an HTTP request. Use a test that matches the failed operation.
Record the requested hostname, resolved address, protocol, port, source host and time. If a proxy answers with an HTTP error, identify which component produced it. In a multi-tier system, the public component can be reachable while its private dependency is unavailable. Network tools become easier to interpret when you draw the separate connections instead of treating a whole website as one machine.
Distinguish devices, filesystems and directory usage
The workshop saves more reports every day. Eventually a write may fail because the filesystem has insufficient available space. Three common tools answer different storage questions. Lsblk describes block devices and their relationships. Df reports filesystem capacity and availability. Du estimates space associated with files and directories. A device, a filesystem and a directory are related concepts, but they are not interchangeable.
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS
df -h .
du -sh inputs reports
The lsblk command is for Linux and requests explicit columns. On a system whose version lacks a named column, consult its supported column list. The df command asks about the filesystem containing the current directory. The du command focuses on the two small directories from our exercise. Their values can differ from the visible character counts in the files because storage is allocated in units and filesystem behavior varies.
On EC2, increasing the capacity of an underlying EBS volume and making that space available through the guest filesystem can involve separate steps. The current device size alone does not prove that the mounted filesystem has grown. Inspect the storage layers and follow the relevant operating-system and filesystem procedure when performing that task in a dedicated lab.
Differences between df and du deserve investigation. Deleted files can remain open in a process. Permission restrictions can prevent a directory scan from reading everything. Filesystem metadata, reserved space, mount boundaries and file allocation can also matter. Removing unfamiliar directories to make the figures agree is not a diagnosis. First establish what each command measured and which filesystem is actually full.
Storage cleanup should follow a retention decision. A large report might be essential evidence. A small-looking directory might contain millions of entries. Keep the business meaning, recoverability and storage measurement together when choosing what to archive or remove.
Schedule work only after its manual result is understood
The instructor wants the report at eight each morning. A scheduler can start the command without a person opening a terminal. Cron is a common Linux scheduling facility. A user crontab normally has five time fields followed by the command. System crontab formats can include an additional user field, so copying a line between formats without understanding it can change its meaning.
0 8 * * * /absolute/path/to/report-script
This is a reading example, not a job to install for the temporary workspace. In the usual five-field format it requests execution at minute zero of hour eight on the matching calendar days. The scheduler’s timezone and handling of clock changes matter. A machine configured for UTC may not run at eight in the instructor’s local timezone. Write the intended timezone alongside the schedule.
A scheduled job may run with a different environment and working directory from your interactive terminal. Use explicit input and output paths and provide required configuration deliberately. A program that succeeds because you previously changed directories can fail when a scheduler starts it elsewhere. Likewise, an exported value in your terminal may not exist in the scheduled process.
Decide what happens when one run takes longer than the interval before the next run. Two processes might write the same report simultaneously. A suitable locking or job-coordination mechanism can prevent unwanted overlap, but it must match the workflow. Also decide where errors go and how somebody will know that a report is missing.
First run the exact command manually with representative input and expected permissions. Then test its failure behavior. Only after these results are understood should you install a schedule in an approved training environment. Automation repeats behavior; it does not make an incorrect calculation correct.
Pass configuration deliberately between processes
An environment variable is a named value passed into a process when it starts. Programs can use such values for configuration. A shell variable and an exported environment variable are related but different: a variable known only to the current shell is not automatically available to an external child program. Exporting it makes it part of the environment inherited by subsequently launched children.
WORKSHOP_LABEL=training
export WORKSHOP_LABEL
bash -c 'printf "%s\n" "$WORKSHOP_LABEL"'
unset WORKSHOP_LABEL
The child Bash process should print training. Removing the value afterward changes the current shell’s configuration for later children. It does not reach into an already running process and erase its copy. Another terminal session does not automatically receive this value either. Process creation and configuration determine inheritance.
Configuration can make one program reusable for a training and a production environment, but the value must still be validated. If an expected input directory is absent, a script should report that condition instead of silently choosing a different directory. Give task-specific values meaningful names. Avoid replacing system variables with unrelated meanings because programs already rely on their established purpose.
Do not print a complete process environment into a public debugging report without considering its contents. Real environments can contain credentials or private configuration. For this course, inspect only the harmless named value created by the exercise. In AWS applications, use the intended identity and secret-management mechanisms and avoid copying long-lived credentials into lesson scripts.
A configuration change also needs a delivery plan. Editing a file or exporting a value in your own shell may not change a service that is already running. Identify how the target program receives configuration and when it reads it. This explains many cases where a student changes a setting but the application continues using its earlier value.
Keep local and remote paths distinct during SSH and file transfer
SSH establishes an authenticated encrypted connection to a remote SSH server. Once you open a remote shell, commands run on that remote machine unless you explicitly leave it or use a separate local terminal. Run hostname and pwd when the boundary is unclear. A local laptop path and a path on EC2 can look similar while referring to completely different files.
Successful access depends on several independent pieces: the intended server address, an allowed network path, the SSH server, the correct account and a suitable authentication method. The remote host identity matters too. Verify a new host key through a trusted channel according to the lab’s instructions. Do not treat a changed host-key warning as something to remove without investigating why it changed.
Scp transfers files using SSH-related authentication and transport. Modern OpenSSH scp normally uses SFTP by default. A remote operand identifies a host and a path, while a local operand identifies a path on your current machine. Before running a transfer, write a sentence stating its direction: copy the local reviewed report into the remote training directory, or download a remote report into a local review folder.
For the main exercise, no remote host is needed. Plan the intended source and destination on paper. In the dedicated SSH lesson, use a disposable instance and its documented account name. A transfer reporting success proves a copy operation completed under its conditions; it does not prove a website serves the copied file or that a service has loaded a new configuration.
Observe resource use over the period that matters
A program is stored code; a process is a running instance of work. One application can use several processes, and a process can contain multiple threads. Tools such as ps provide a snapshot, while top repeatedly refreshes resource information. A process identifier is useful for the current observation but can be reused later, so record the command and start context when diagnosing a specific job.
High CPU usage can mean useful computation. Low CPU usage can mean a program is waiting for storage, a network response or a lock. Memory figures also need interpretation: virtual address space, resident memory and shared memory describe different things. Avoid concluding that one process is faulty solely because it appears first in a sorted display.
For the workshop, compare the period when a report is normally generated with the period when students noticed slowness. Record the input size and run duration. A larger input can explain a longer calculation; a missing dependency can explain an idle process. A single screenshot taken after the incident may not capture either condition.
If a process needs to be stopped in a dedicated lab, first identify the intended process and prefer its normal shutdown mechanism. A forceful termination prevents normal cleanup and may leave partial output. The purpose of monitoring is to understand resource behavior and verify a targeted action, rather than to terminate whichever process happens to use the most memory.
Make the report repeatable with a small checked script
A shell script saves a sequence of commands so it can be reviewed and repeated. It still needs explicit inputs and failure handling. The following script reads our controlled measurement file and prints the failed-test count and average. It does not decide its input based on whichever directory happens to be current. The input path is an argument, making the dependency visible to the caller.
cat > report.sh <<'SCRIPT'
#!/usr/bin/env bash
if [ "$#" -ne 1 ]; then
printf '%s\n' 'Usage: report.sh input.csv' >&2
exit 2
fi
report_input=$1
if [ ! -r "$report_input" ]; then
printf '%s\n' 'Input is not readable' >&2
exit 3
fi
awk -F, '
NR > 1 && $3 == "FAIL" { total += $2; count++ }
END {
if (count > 0)
printf "Failed tests: %d; average pressure: %.1f\n", count, total / count
else
print "No failed tests in this input"
}
' "$report_input"
SCRIPT
bash report.sh inputs/pumps.csv
Expect the same count and average as before. The argument-count check provides a specific message when the caller forgets the input. The readability check addresses another predictable failure. Diagnostics go to standard error, leaving standard output available for the report itself. The last command’s status becomes the script’s result in this simple arrangement.
Run it once without an argument and once with a missing filename. Capture the status immediately after each call, before another command replaces the shell’s last-status value. The expected statuses are two and three. These tests demonstrate deliberate behavior, rather than assuming that every failed command automatically stops a script.
This remains a teaching script for the defined simple input format. It has not become a universal production CSV validator. Its next improvements would validate the header, field count, numeric pressure and allowed result values, and make rejected records visible. A production workflow would also decide how to publish the output only after a successful run, so a partial report does not replace a previous valid result.
Finish the lab with evidence and a clear cleanup boundary
Prepare a short report about the exercise itself. Record the original four measurements, the two failed identifiers, the expected average, the transformed review labels and the restored-file comparison. Include the script’s results for correct input, missing input and missing argument. Another student should be able to follow your evidence without assuming that a command succeeded merely because it was typed.
If a result differs, return to the earliest point where your observation and prediction diverge. Check whether the input was created exactly, whether the terminal is still in the workspace and whether a later exercise changed a file. Do not reset every part at once; doing so can hide which assumption caused the difference.
Cleanup applies only to the temporary path created for this exercise. Print the stored workspace path and inspect its contents. If it matches the recorded lab directory, remove the known sample files and archive, then remove the now-empty directories with rmdir. Remove any extra practice file you deliberately created, such as the filename containing a space. Leave the workspace before removing its root directory. If unexpected files exist, inspect them instead of expanding the deletion command.
The lab created no AWS resources, services or scheduled jobs. Its optional service, network and storage examples were observations on an existing training environment. This separation makes cleanup understandable: remove the exercise’s own files, and preserve unrelated host configuration.
Explain the reasoning in an interview
A report is empty. Does that prove the input had no failed tests?
No. I would check that the intended input was readable, inspect the filter and its exit status, and confirm that the output writer succeeded. A valid search with no matches differs from a failed search. I would reproduce the calculation on a small known sample before trusting the empty result.
A service is enabled but its website does not answer. Explain the distinction.
Enabled describes startup integration, not current application health. I would inspect the service state and recent journal entries, then check its listener and application response. Even an active process can fail to complete requests because of its configuration or a dependency.
Why can a shell pipeline appear successful after an earlier command fails?
In Bash’s default behavior, the pipeline status comes from its final command. A later program may successfully process empty input despite an earlier failure. Pipefail changes status reporting, but I still need diagnostics and stage-specific checks to understand the actual cause and verify the output.
How would you demonstrate that a backup is useful?
I would identify its contents and capture time, restore it into an isolated location and verify the recovered data or application behavior. For our fixture, comparing restored bytes is a useful check. A real database requires an appropriate consistency and recovery procedure as well as a stored backup file.
Why might a scheduled command fail while the same command works interactively?
The scheduler can provide a different identity, working directory, environment and command-search path. I would make the required paths and configuration explicit, inspect captured errors and test under the intended execution conditions. I would also check timing, overlap and permissions rather than assuming the scheduler ignored the job.
Check your understanding with small predictions
A grep search reads a valid file and finds no matches. Is this necessarily a file-read error?
Answer and explanation
No. No matches is a defined search outcome. Compare its status and diagnostics with the result of attempting to read a missing file. The distinction matters when an empty count is a valid report result.
You preview a sed substitution without an in-place option or output redirection. Which file was changed?
Answer and explanation
The command displays transformed output; it does not thereby change the source file. Saving the display to a new path is a separate action. Confirm the original contents when preservation is part of the exercise.
The EBS device is larger after resizing, but df still shows the old filesystem capacity. Are the two observations contradictory?
Answer and explanation
No. Device capacity and filesystem capacity describe different storage layers. Investigate the partition and filesystem procedure for that environment. Do not assume a larger block device automatically completed every guest-level growth step.
A colleague exports a variable in one terminal. Must an already running service immediately see the new value?
Answer and explanation
No. Environment values are inherited when processes are started through the relevant configuration. A separate running service does not automatically receive changes from that terminal. Identify how the service obtains its settings.
Revision cards for the complete workflow
- Search text or discover files
- Grep selects text records. Find discovers filesystem entries. Choose the operation that matches the question before combining them.
- Transform or replace
- A displayed transformation is not a changed input. Save a separate result, inspect it and make replacement a deliberate operation.
- Current state or startup policy
- Active and enabled answer different service questions. Verify the application’s useful behavior in addition to manager state.
- Device or filesystem
- Lsblk, df and du observe different storage layers. Explain their scope before comparing their numbers.
- Manual or scheduled execution
- A scheduler needs explicit paths, configuration and error reporting. Test the intended execution conditions before relying on repetition.
- Archive or recovery
- Creating an archive stores a collection. A restore test demonstrates whether the expected data can actually be recovered.
Primary references
- GNU grep patterns, options and exit status
- GNU findutils manual
- GNU awk introduction
- GNU sed editing and output
- Bash pipeline behavior and redirection
- GNU tar archive and extraction behavior
- systemctl state and startup operations and journalctl
- Block-device inspection with lsblk
- Filesystem capacity with df and file usage with du
- Cron table formats and execution environment
- OpenSSH manuals and OpenSSH release notes
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioPune Fintech Labs is a finance business in Pune. Rohan Kulkarni looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 10
Easy Check memory
If RAM is full the server slows down or kills apps.
Show used and free memory in human-readable units.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Find errors in a log
grep shows only the lines that contain a word, so you find problems fast.
Show every line containing ERROR in /var/log/punefintech/app.log.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Count matching lines
A count tells you quickly how often something happened today.
Count how many lines in /var/log/nginx/access.log contain " 404 ".
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Case-insensitive search with line numbers
Logs mix "Timeout" and "TIMEOUT". Line numbers help you open the exact spot.
Search for timeout in /var/log/punefintech/api.log, ignoring upper/lower case, and show line numbers.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Find files by name
find searches folder trees for files that match a pattern.
Find all files ending in .log under /var/log/punefintech.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Permission number
Key files must be private.
What chmod number gives the owner read+write and nobody else anything?
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Find big files
When the disk is full, find large files first.
Find files bigger than 100 MB anywhere under /var.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Hard Search a whole folder
Settings can hide in any file. A recursive search checks them all.
Find every line that mentions DB_HOST in all files under /etc/punefintech, with line numbers.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Hard Find old files
Old files fill the disk. -mtime +N finds files changed more than N days ago.
Find regular files under /backup/punefintech that were changed more than 56 days ago.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Hard Find a running process
A pipe sends the full process list into grep so you see only what matters.
List all processes and show only the lines that contain node.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.