Lab 2 - Linux Commands II

Updated 4 Oct 2026

Lab Instructions

  • Attendance checked at the beginning of class
  • Login credentials:
    • Username: student
    • Password: Siit@1992
  • ✔ 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 > filename

Example:

ls -l /usr/bin > ls-output.txt
  • Creates long listing of /usr/bin directory
  • Sends results to file ls-output.txt instead of screen
  • Can verify file creation with ls command

Viewing the file:

less ls-output.txt

Analogy: 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 completely

    ls > ls-output.txt  # Overwrites existing file
  • Appending: Use >> to append instead of overwrite

    ls -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> filename

Boxed Formula:
command 2> error-file.txt\boxed{\text{command } 2> \text{ error-file.txt}}

Example:

ls -l /abc/def 2> ls-output.txt
less ls-output.txt

Now 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:
Command1 | Command2\boxed{\text{Command1 | Command2}}

The pipe operator | (vertical line) passes output from Command1 as input to Command2.

Example:

ls -l | less

Output 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_N

Multiple 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.txt

Steps:

  1. Type text: "I am a student in the School of ICT."
  2. Exit and save:
    • Press CTRL + X
    • Press y (yes to save)
    • Press Enter

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.txt

Steps:

  1. Type text: "SIIT, Thammasat University"
  2. Save: Click Save button
  3. 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:
cat File1 File2 > OutputFile\boxed{\text{cat File1 File2 > OutputFile}}

Example:

cat Ex1.txt Ex2.txt > Ex3.txt

Combines 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:
sort OriginalFile > OutputFile\boxed{\text{sort OriginalFile > OutputFile}}

Example:

  1. Create file Ex4.txt with contents:

    c
    c
    a
    b
    b
    2
    
  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:
sort OriginalFile | uniq > OutputFile\boxed{\text{sort OriginalFile | uniq > OutputFile}}

Example:

sort Ex4.txt | uniq > Ex6.txt
cat Ex6.txt

Output:

2
a
b
c

Count repeated lines:
sort OriginalFile | uniq -c > OutputFile\boxed{\text{sort OriginalFile | uniq -c > OutputFile}}

Example:

sort Ex4.txt | uniq -c > Ex7.txt
cat Ex7.txt

Output:

   1 2
   1 a
   2 b
   2 c

Analogy: uniq is like removing duplicate items from a shopping list. The -c flag 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 filename

Example:

wc Ex4.txt

Output:

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

CommandShort Description
grepPrint lines matching a pattern
head/tailPrint first/last part of files
cutRemove sections from each line
pasteMerge lines of files
joinJoin lines of two files on common field
commCompare two sorted files, line by line
diffCompare 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 aux

Lists all running processes with details.

Process Attributes:

Column HeaderContents
USERUsername of process's owner
PIDProcess ID Number
%CPUPercentage of CPU the process is using
%MEMPercentage of memory the process is using
VSZVirtual memory allocated (KBytes)
RSSPhysical memory usage (Resident Set Size in KBytes)
TTYTerminal associated with this process
STATProcess Status Code (R=Running, Z=Zombie, T=Terminated, S=Sleep, s=Session Handler, I=Multi-Thread)
STARTTime when process started
TIMETotal CPU Usage
COMMANDName 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:

  1. Type xlogo and press Enter
  2. Small window appears, shell prompt doesn't return
  3. Press CTRL-C to 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 number
  • 4681 = 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 %JobNumber

Example:

fg %1

Check job number:

jobs

Analogy: 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:

  1. With process in foreground, press CTRL-Z
  2. Process stops but doesn't terminate

Verify process still exists:

ps aux  # xlogo still in process list

Resume and terminate:

fg %1      # Bring to foreground
# Press CTRL-C to terminate

Analogy: 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:
kill PID#\boxed{\text{kill PID\#}}

Example:

xlogo &          # Start in background
[1] 4810
ps aux           # Find PID
kill 4810        # Terminate process
[1]+ Terminated  xlogo

Analogy: 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:

  1. Write the script
  2. Make it executable
  3. 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
  • 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 -l

You'll see no x in permissions (not executable).

Change permissions:
chmod 755 FileName\boxed{\text{chmod 755 FileName}}

Example:

chmod 755 MyScript1
ls -l MyScript1

Permission Settings:

  • 755: Everyone can execute
  • 700: 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:

./MyScript1

Output:

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 MyScript2

Step c) Execute with Arguments

./MyScript2 Inp1 Inp2

Output:

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 20

Analogy: 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:
VarName=value\boxed{\text{VarName=value}}
or
VarName="string"\boxed{\text{VarName="string"}}

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
fi

Important Rules:

  • CONDITION is placed between square brackets [ ]
  • Space required after [
  • Space required before ]
  • fi indicates end of if statement

Comparison Operators

For Strings:

SyntaxMeaning
var1 = var2Is first variable equal to second?
var1 != var2Is first variable not equal to second?

For Numbers:

SyntaxMeaning
var1 -eq var2Is first variable equal to second?
var1 -ge var2Is first variable greater than or equal to second?
var1 -gt var2Is first variable greater than second?
var1 -le var2Is first variable less than or equal to second?
var1 -lt var2Is first variable less than second?
var1 -ne var2Is 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
    1. Name (first argument: $1)
    2. Age (second argument: $2)
    3. Output file path (third argument: $3)

Behavior:

  1. Greet with "Hello" followed by name
  2. Check if age ≤ 0
    • If yes: Display "Error: age must be more than zero." and exit
    • If no: Continue to step 3
  3. Save (append) information to output file specified in third argument
  4. 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.txt

Expected 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.txt

Expected 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 cmd2

Text 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, bytes

Process 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 PID

Shell 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
fi

Comparison 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 equal

Key Takeaways

  1. I/O Redirection separates normal output (stdout) from errors (stderr), allowing precise control over where data goes

  2. Pipelines enable powerful command chaining—output from one command becomes input to the next

  3. Text processing tools (cat, sort, uniq, wc) are fundamental for data manipulation in Linux

  4. Process management allows multitasking through foreground/background control and process termination

  5. Shell scripts automate repetitive tasks by combining commands, variables, and control structures

  6. Always use spaces correctly in shell scripts—especially around brackets in conditions and no spaces around = in assignments

  7. The shebang (#!/bin/bash) must be the first line of every shell script to specify the interpreter