Lab Instructions
- Attendance checked at the beginning of class
- Login credentials:
- Username:
student - Password:
Siit@1992
- Username:
- ✔ sign identifies exercises to complete
- Some exercises require TA signature
- Show completed Lab Sheet to TA
- 10-minute quiz at end of class
- Submit last page to TA at end of class
Exercise 1: Input/Output (I/O) Redirection
Overview
Linux allows redirection of command input and output to/from files.
Key Concepts:
- Standard Input (stdin): Input facility, default attached to keyboard
- Standard Output (stdout): Special file for command results
- Standard Error (stderr): Special file for status/error messages
Analogy: Think of stdin, stdout, and stderr as three different pipes. stdin brings water (data) in, stdout carries the clean processed water out, and stderr is a separate pipe that carries error messages—keeping them separate from normal output.
By default, both stdout and stderr display on screen (not saved to disk). I/O redirection changes where output goes and where input comes from.
1.1) Redirect Standard Output to a File
Purpose: Redefine where standard output goes
Syntax:
command > filenameExample:
ls -l /usr/bin > ls-output.txt- Creates long listing of
/usr/bindirectory - Sends results to file
ls-output.txtinstead of screen - Can verify file creation with
lscommand
Viewing the file:
less ls-output.txtAnalogy: Using
>is like redirecting a water hose from watering your lawn to filling a bucket. The water (output) goes to a different destination.
Important Notes:
-
Overwriting: Using
>on existing file overwrites it completelyls > ls-output.txt # Overwrites existing file -
Appending: Use
>>to append instead of overwritels -l >> ls-output.txt # Adds to end of file
Error Behavior:
ls -l /abc/def > ls-output.txt- If command produces error, file size becomes 0 bytes
- Error messages still appear on screen
>only redirects stdout, not stderr
1.2) Redirect Standard Error to a File
Purpose: Redirect error messages to a file instead of screen
Syntax:
command 2> filenameBoxed Formula:
Example:
ls -l /abc/def 2> ls-output.txt
less ls-output.txtNow the error message is captured in the file instead of displayed on screen.
1.3) Pipelines
Purpose: Connect standard output of one command to standard input of another
Syntax:
The pipe operator | (vertical line) passes output from Command1 as input to Command2.
Example:
ls -l | lessOutput of ls -l is sent to less program for viewing.
Analogy: Pipelines are like assembly lines in a factory. The output from one station (command) becomes the input for the next station, allowing complex processing through simple steps.
Multiple Pipes:
Command1 | Command2 | ... | Command_NMultiple commands can be chained together, with each command processing the output of the previous one.
Exercise 2: Create/Edit Text Files with Text Editors
Overview
Text editors create various file types (.txt, .c, etc.). Two popular editors:
- nano: Command-line interface editor
- gedit: Desktop graphical editor
2.1) Using nano Text Editor
Starting nano:
nano Ex1.txtSteps:
- Type text: "I am a student in the School of ICT."
- Exit and save:
- Press
CTRL + X - Press
y(yes to save) - Press
Enter
- Press
Verifying:
ls # Check file was created
less Ex1.txt # View contents (press 'q' to exit)Analogy: nano is like Notepad—simple, straightforward, and gets the job done without fancy features. It's great for quick edits in the terminal.
2.2) Using gedit Text Editor
Starting gedit:
gedit Ex2.txtSteps:
- Type text: "SIIT, Thammasat University"
- Save: Click Save button
- Exit: Select File > Quit
Verifying:
ls # Check file was created
less Ex2.txt # View contents (press 'q' to exit)Analogy: gedit is like TextEdit or Notepad++—a graphical editor with menus and buttons, more user-friendly for those who prefer GUI over command-line.
Exercise 3: Text Processing
Overview
UNIX-like systems rely heavily on plain-text files for data storage. Tools for manipulating text files are critical.
3.1) Command: cat
Purpose: Concatenate files and print on standard output
View file contents:
cat Ex1.txt✔ Exercise: Use cat to view contents of Ex2.txt and record what you see.
Concatenate (combine) files:
Example:
cat Ex1.txt Ex2.txt > Ex3.txtCombines Ex1.txt and Ex2.txt into Ex3.txt.
Analogy: cat is like a copy-paste function. It reads files and pastes their contents either to your screen or into another file. When combining files, it's like stapling documents together.
3.2) Command: sort
Purpose: Sort lines in text file in numerical and alphabetical order
Syntax:
Example:
-
Create file
Ex4.txtwith contents:c c a b b 2 -
Sort the file:
sort Ex4.txt > Ex5.txt cat Ex5.txt
Output:
2
a
b
b
c
c
Analogy: sort is like organizing a deck of cards. It arranges everything in order—numbers first, then letters alphabetically. Duplicates stay as separate cards.
3.3) Command: uniq
Purpose: Omit or report repeated lines in text files
Omit repeated lines:
Example:
sort Ex4.txt | uniq > Ex6.txt
cat Ex6.txtOutput:
2
a
b
c
Count repeated lines:
Example:
sort Ex4.txt | uniq -c > Ex7.txt
cat Ex7.txtOutput:
1 2
1 a
2 b
2 c
Analogy: uniq is like removing duplicate items from a shopping list. The
-cflag counts how many times each item appeared before removing duplicates. Note: uniq only removes adjacent duplicates, which is why we pipe through sort first!
3.4) Command: wc
Purpose: Display number of lines, words, and size (in bytes) of file
Syntax:
wc filenameExample:
wc Ex4.txtOutput:
6 6 12 Ex4.txt
Interpretation:
- 6 lines
- 6 words
- 12 bytes
- Filename: Ex4.txt
Analogy: wc (word count) is like the status bar in Microsoft Word that shows you statistics about your document—how many lines, words, and the file size.
3.5) Other Text Processing Commands
| Command | Short Description |
|---|---|
grep | Print lines matching a pattern |
head/tail | Print first/last part of files |
cut | Remove sections from each line |
paste | Merge lines of files |
join | Join lines of two files on common field |
comm | Compare two sorted files, line by line |
diff | Compare files, line by line |
Exercise 4: Processes
Overview
Modern operating systems are multitasking—they create illusion of doing multiple things simultaneously by rapidly switching between executing programs.
Key Concept:
- Process: An instance of a running program
- Linux kernel manages processes
- Tools available for: listing, monitoring, and stopping processes
Analogy: Processes are like apps on your smartphone. Even though you see one app at a time, many are running in the background. The OS quickly switches between them, making it seem like they're all running simultaneously.
4.1) Listing Processes with ps
Command:
ps auxLists all running processes with details.
Process Attributes:
| Column Header | Contents |
|---|---|
| USER | Username of process's owner |
| PID | Process ID Number |
| %CPU | Percentage of CPU the process is using |
| %MEM | Percentage of memory the process is using |
| VSZ | Virtual memory allocated (KBytes) |
| RSS | Physical memory usage (Resident Set Size in KBytes) |
| TTY | Terminal associated with this process |
| STAT | Process Status Code (R=Running, Z=Zombie, T=Terminated, S=Sleep, s=Session Handler, I=Multi-Thread) |
| START | Time when process started |
| TIME | Total CPU Usage |
| COMMAND | Name of command, including arguments if any |
4.2) Controlling Processes
Test Program: We'll use xlogo (opens a small window) for demonstrations.
Interrupting a Process
Steps:
- Type
xlogoand press Enter - Small window appears, shell prompt doesn't return
- Press
CTRL-Cto interrupt and terminate program
Analogy: CTRL-C is like hitting the emergency stop button on a machine. It immediately halts the process.
Putting a Process in the Background
Purpose: Get shell prompt back without terminating program
Syntax:
command &Example:
xlogo &Output:
[1] 4681
[1]= Job number4681= PID (Process ID)
Now you can run other commands while xlogo runs in background!
Analogy: Running a process in the background is like starting your washing machine and then going to do other chores. The machine keeps running while you're free to do something else.
Returning Process to Foreground
Syntax:
fg %JobNumberExample:
fg %1Check job number:
jobsAnalogy: Bringing a process to the foreground is like putting a paused video game back on your TV screen—it becomes your focus again.
Stopping (Pausing) a Process
Steps:
- With process in foreground, press
CTRL-Z - Process stops but doesn't terminate
Verify process still exists:
ps aux # xlogo still in process listResume and terminate:
fg %1 # Bring to foreground
# Press CTRL-C to terminateAnalogy: CTRL-Z is like hitting pause on a video. The video is still loaded and ready, just not playing. You can resume it later or stop it completely.
Killing a Running Process
Purpose: Terminate a running process (doesn't affect stopped/paused processes)
Syntax:
Example:
xlogo & # Start in background
[1] 4810
ps aux # Find PID
kill 4810 # Terminate process
[1]+ Terminated xlogoAnalogy: kill is like force-quitting an application. When an app freezes and won't respond to normal close commands, you use Task Manager (Windows) or Activity Monitor (Mac) to force it to close—that's essentially what kill does.
Process State Diagram
$ cmd
↓
┌──────────────┐
│ Foreground │←────── ctrl-C
└──────────────┘
↓ ↑
ctrl-Z fg
↓ ↑
┌──────────────┐ ┌──────────┐
│ Stopped │───fg──→│ Killed │
└──────────────┘ └──────────┘
↓ ↑ ↑
bg stop job# kill job#
↓ ↑ ↑
┌──────────────┐ │
$ cmd & ──→│ Background │──────────┘
└──────────────┘
Exercise 5: Writing Simple Shell Scripts
Overview
Shell Script: A series of commands written in a file. The shell reads commands from the file as if you typed them in terminal.
Analogy: A shell script is like a recipe. Instead of remembering and typing each step every time you cook, you write down all the steps once. Then you just follow the recipe (run the script) whenever you need it.
5.1) Your First Shell Script
Three Requirements:
- Write the script
- Make it executable
- Execute it
Step a) Write a Script
Filename: MyScript1 (no extension)
Contents:
#!/bin/bash
# This is a comment.
echo 'Hello World!'Line Explanations:
- Line 1:
#!/bin/bash(shebang)- Tells system which interpreter to use
- Must start with
#!character sequence - Must be first line (no blank line before it)
- Line 2:
# This is a comment.- Comments start with
# - Ignored by interpreter
- Comments start with
- Line 3:
echo 'Hello World!'- Command to execute
Analogy: The shebang (#!) is like the programming language declaration at the top of code. It tells the computer "Hey, use the bash interpreter to read this file!"
Step b) Make Script Executable
Check current permissions:
ls -lYou'll see no x in permissions (not executable).
Change permissions:
Example:
chmod 755 MyScript1
ls -l MyScript1Permission Settings:
755: Everyone can execute700: Only owner can execute
Note: Scripts must be readable to be executed.
Analogy: chmod is like changing a document from "view only" to "editable and runnable." By default, text files are just readable—you need to give them execute permission to run as programs.
Step c) Execute the Script
From same directory:
./MyScript1Output:
Hello World!
5.2) Shell Script with Inputs (Arguments)
Purpose: Receive input from command line when running script
Step a) Write Script with Arguments
Filename: MyScript2
Contents:
#!/bin/bash
echo "The first argument is $1 and the second argument is $2."
echo "The command itself is $0"Command Line Arguments:
$0: Stores the script name (e.g.,./MyScript2)$1: Stores first argument$2: Stores second argument$3,$4, etc.: Additional arguments
Step b) Make Executable
chmod 755 MyScript2
ls -l MyScript2Step c) Execute with Arguments
./MyScript2 Inp1 Inp2Output:
The first argument is Inp1 and the second argument is Inp2.
The command itself is ./MyScript2
✔ Exercise: Run the following and record result:
./MyScript2 ABC 20Analogy: Command line arguments are like filling in blanks in a form. The script is the form template, and the arguments are the specific information you fill in each time you use it.
5.3) Shell Script with Variable
Purpose: Store and use values in variables
Storing Values in Variables
Syntax:
or
Important Rules:
- No spaces around
=sign - No data type declaration needed
- Variable name touches the
=sign - Value/string touches the
=sign
Examples:
X=1
Y="NetLab"Using Variable Values
Syntax: Put $ in front of variable name
Example:
echo "The value of X is $X."
echo "The value of Y is $Y."Analogy: Variables are like labeled boxes. You put a value in the box (assignment), and use the label to retrieve what's inside later (using $).
Example Script
Filename: MyScript3
Contents:
#!/bin/bash
X=1
Y="NetLab"
echo "The value of X is $X."
echo "The value of Y is $Y."✔ Exercise:
- Make script executable (write command)
- Execute script and record output
5.4) Shell Script with "if...then" Statements
Purpose: Perform actions when certain conditions are true
Syntax:
if [ CONDITION ] ; then
lines of commands
else
lines of commands
fiImportant Rules:
- CONDITION is placed between square brackets
[ ] - Space required after
[ - Space required before
] fiindicates end of if statement
Comparison Operators
For Strings:
| Syntax | Meaning |
|---|---|
var1 = var2 | Is first variable equal to second? |
var1 != var2 | Is first variable not equal to second? |
For Numbers:
| Syntax | Meaning |
|---|---|
var1 -eq var2 | Is first variable equal to second? |
var1 -ge var2 | Is first variable greater than or equal to second? |
var1 -gt var2 | Is first variable greater than second? |
var1 -le var2 | Is first variable less than or equal to second? |
var1 -lt var2 | Is first variable less than second? |
var1 -ne var2 | Is first variable not equal to second? |
Note: Use = for strings, use -eq for numbers
Analogy: if-then statements are like traffic lights. IF the light is red, THEN stop. ELSE (if it's not red), go. The condition determines which action to take.
Example Script
Filename: MyScript4
Contents:
#!/bin/bash
St="Friday"
if [ $St = "Friday" ] ; then
echo "It is Friday."
echo "Let us have a party."
else
echo "Not Friday."
fi✔ Exercise: Execute this script and record output. Show results to TA for signature.
5.5) Practice: Creating Shell Script from Requirements
Assignment: Write a shell script to create a user setting file
Requirements:
- Script name:
saveprofile.sh - Arguments: 3 required
- Name (first argument:
$1) - Age (second argument:
$2) - Output file path (third argument:
$3)
- Name (first argument:
Behavior:
- Greet with "Hello" followed by name
- Check if age ≤ 0
- If yes: Display "Error: age must be more than zero." and exit
- If no: Continue to step 3
- Save (append) information to output file specified in third argument
- Display confirmation message with name, age, and output file path
File Requirements:
- Data path:
/home/student/data/setting.txt - Create directory if it doesn't exist
Test Cases
Test Case 1:
saveprofile.sh john 35 /home/student/data/setting.txtExpected Screen Output:
Hello john!
Name is john and age is 35.
The output is in /home/student/data/setting.txt
Expected File Output:
john, 35
Test Case 2:
saveprofile.sh john -1 /home/student/data/setting.txtExpected Screen Output:
Hello john!
Error: age must be more than zero.
Expected File Output:
No output file
✔ Exercise: Write the shell script and show to TA for signature
References
- W. E. Shotts, The Linux Command Line: A Complete Introduction, No Starch Press, 2012
- C. Negus, Linux Bible, 9th Ed., John Wiley & Sons, 2015
Lab Submission Checklist
Part 1: Lab Exercise Completion
- ☐ Complete all exercises with ✔ marks
- ☐ Get TA signature for verification
- ☐ Show completed Lab Sheet to TA
Part 2: Quiz Answer Sheet
- Questions 1-4: Multiple choice (1 point each)
- Questions 5-6: Short answer (1 point each)
- Questions 7-8: Explanation (2 points each)
- Submit last page to TA at end of class
Quick Reference Card
I/O Redirection
command > file # Redirect stdout to file (overwrite)
command >> file # Redirect stdout to file (append)
command 2> file # Redirect stderr to file
command1 | command2 # Pipe stdout of cmd1 to stdin of cmd2Text Processing
cat file # Display file contents
cat file1 file2 > file3 # Concatenate files
sort file > output # Sort lines
uniq file # Remove duplicate adjacent lines
uniq -c file # Count duplicates
wc file # Count lines, words, bytesProcess Control
ps aux # List all processes
command & # Run in background
jobs # List background jobs
fg %N # Bring job N to foreground
CTRL-C # Terminate foreground process
CTRL-Z # Stop (pause) foreground process
bg %N # Resume job N in background
kill PID # Terminate process by PIDShell Scripting
#!/bin/bash # Shebang (first line)
# comment # Comment line
$0, $1, $2 # Command line arguments
VarName=value # Assign variable
$VarName # Use variable
chmod 755 script # Make executable
./script # Execute script
# If statement structure
if [ condition ] ; then
commands
else
commands
fiComparison Operators
# Strings
[ "$var1" = "$var2" ] # Equal
[ "$var1" != "$var2" ] # Not equal
# Numbers
[ $num1 -eq $num2 ] # Equal
[ $num1 -ne $num2 ] # Not equal
[ $num1 -gt $num2 ] # Greater than
[ $num1 -ge $num2 ] # Greater than or equal
[ $num1 -lt $num2 ] # Less than
[ $num1 -le $num2 ] # Less than or equalKey Takeaways
-
I/O Redirection separates normal output (stdout) from errors (stderr), allowing precise control over where data goes
-
Pipelines enable powerful command chaining—output from one command becomes input to the next
-
Text processing tools (cat, sort, uniq, wc) are fundamental for data manipulation in Linux
-
Process management allows multitasking through foreground/background control and process termination
-
Shell scripts automate repetitive tasks by combining commands, variables, and control structures
-
Always use spaces correctly in shell scripts—especially around brackets in conditions and no spaces around
=in assignments -
The shebang (
#!/bin/bash) must be the first line of every shell script to specify the interpreter