Skip to content
Go back

Linux-M2 - Introduction to Linux Commands

Published:

Overview of Common Linux Shell Commands


1. What is a Shell?

Definition

A shell is a powerful command-line interpreter used in Unix-like operating systems (like Linux and macOS).

Common Shells in Linux

ShellDescription
Bash (/bin/bash)Bourne Again SHell – Default on most Linux distros
shOriginal Bourne shell
kshKornShell – Enhanced version of sh
tcshExtended C Shell with advanced features
zshZ Shell – Modern, feature-rich
fishFriendly Interactive SHell – beginner-friendly

In this course, we will use Bash, the default shell on most Linux systems.

How to Check Your Current Shell

printenv SHELL

Example output:

/bin/bash

If not Bash, you can switch by typing:

bash

2. Applications of Shell Commands

Shell commands are essential for various tasks such as:

Task CategoryExamples
System Infouname, date, whoami
File Managementcp, mv, rm, touch
Directory Navigationls, cd, pwd, mkdir
Text Displaycat, head, tail, echo
Search & Filtergrep, find
Compressiontar, zip, unzip
Networkingcurl, wget, ping, hostname
Performance Monitoringtop, ps, df

3. Common Shell Commands

A. System Information Commands

CommandDescription
whoamiDisplays current username
idShows user and group IDs
unameDisplays OS name and version
psLists running processes
topReal-time system monitoring tool
dfShows disk space usage
man [command]Displays manual/help for any command
datePrints current date and time

B. File Management Commands

CommandDescription
cp file1 file2Copy files or directories
mv file1 file2Move or rename files
rm fileRemove/delete a file
touch fileCreate an empty file or update timestamp
chmod permissions fileChange file access permissions
wc fileCount lines, words, characters in a file
grep "pattern" fileSearch for text within a file

C. Directory Navigation Commands

CommandDescription
lsList contents of current directory
find . -name "*.txt"Find files matching a pattern
pwdPrint working (current) directory
mkdir dir_nameMake a new directory
cd dir_nameChange to another directory
rmdir dir_nameRemove an empty directory

D. File Content Viewing Commands

CommandDescription
cat file.txtConcatenate and print full file content
more file.txtView file content one page at a time
head file.txtShow first few lines of a file
tail file.txtShow last few lines of a file
echo "text"Print text or variable values to terminal

E. File Compression & Archiving

CommandDescription
tar -cvf archive.tar file1 file2Archive files into .tar
tar -xvf archive.tarExtract from .tar file
zip archive.zip file1 file2Compress files into .zip
unzip archive.zipExtract .zip archive

F. Networking Commands

CommandDescription
hostnameShow system hostname
ping google.comTest network connectivity
ifconfigConfigure or view network interfaces
curl http://example.comTransfer data from a URL
wget http://example.com/file.txtDownload files from the web

4. Running Linux on Windows

You can run Linux commands on a Windows machine using these methods:

MethodDescription
Dual BootInstall Linux alongside Windows on separate partitions
Virtual Machine (VM)Run Linux inside a VM like VirtualBox or VMware
Linux Emulator (e.g., Cygwin)Run Linux tools in a simulated environment
Windows Subsystem for Linux (WSL)Native Linux compatibility layer on Windows 10/11

5. Summary

✅ The role of a shell in Linux as both a command interpreter and scripting tool.
✅ How to check and switch shells using commands like printenv SHELL and bash.
✅ The main applications of shell commands across system info, file management, networking, and automation.
✅ The most common shell commands grouped by function for easy reference.


Quick Reference Table

PurposeCommand
User Infowhoami, id
System Infouname, date, top, df
File Opscp, mv, rm, touch, chmod, grep
Dir Navigationls, cd, pwd, mkdir, rmdir, find
View Contentcat, head, tail, more, echo
Compressiontar, zip, unzip
Networkingcurl, wget, ping, hostname, ifconfig


🔧 Linux Shell Commands Cheat Sheet

This cheat sheet includes common Linux shell commands, their syntax, and examples. Designed for quick reference and learning.


🧑‍💻 Basic Navigation

CommandDescriptionExample
pwdPrint Working Directorypwd/home/user/documents
cd <dir>Change Directorycd /home/user
lsList files in current directoryls
ls -lLong listing formatls -l
ls -aShow hidden filesls -a

🗂️ File & Directory Management

CommandDescriptionExample
touch <file>Create an empty filetouch myfile.txt
mkdir <dir>Make a new directorymkdir myfolder
cp <src> <dest>Copy files/dirscp file.txt backup/
mv <src> <dest>Move or rename filesmv old.txt new.txt
rm <file>Remove/delete a filerm temp.txt
rm -r <dir>Remove a directoryrm -r myfolder
rmdir <dir>Remove an empty directoryrmdir empty_folder

📄 Viewing and Editing Files

CommandDescriptionExample
cat <file>View entire filecat myfile.txt
more <file>View file page by pagemore bigfile.txt
head <file>Show first 10 lineshead myfile.txt
tail <file>Show last 10 linestail myfile.txt
nano <file>Edit file using nanonano notes.txt
echo "<text>" > <file>Write text to a fileecho "Hello" > hello.txt

🔍 Searching and Filtering

CommandDescriptionExample
grep "<pattern>" <file>Search for pattern in filegrep "error" log.txt
find <path> -name "<pattern>"Find files matching namefind . -name "*.log"
wc <file>Count lines, words, characterswc myfile.txt

🧰 System Information

CommandDescriptionExample
whoamiShow current userwhoami
idShow user and group IDsid
uname -aShow OS infouname -a
dateShow current date/timedate
topReal-time process monitortop
df -hDisk space usagedf -h
psList running processesps

📦 Compression & Archiving

CommandDescriptionExample
tar -cvf <archive.tar> <files>Create tar archivetar -cvf backup.tar *.txt
tar -xvf <archive.tar>Extract tar archivetar -xvf backup.tar
zip <archive.zip> <files>Compress fileszip docs.zip *.docx
unzip <archive.zip>Extract zip archiveunzip docs.zip

🌐 Networking

CommandDescriptionExample
hostnameShow system hostnamehostname
ping <host>Test network connectionping google.com
ifconfigShow network interfaces (deprecated)ifconfig
ip addrAlternative to ifconfigip addr show
curl <url>Download from URLcurl http://example.com
wget <url>Download and save filewget http://example.com/file.txt

💾 Package Management

Debian/Ubuntu (.deb)

CommandDescriptionExample
sudo apt updateUpdate package listsudo apt update
sudo apt upgradeUpgrade all packagessudo apt upgrade
sudo apt install <pkg>Install a packagesudo apt install curl

Red Hat/CentOS/Fedora (.rpm)

CommandDescriptionExample
sudo yum updateUpdate all packagessudo yum update
sudo yum install <pkg>Install a packagesudo yum install wget

🖥️ Shell Utilities

CommandDescriptionExample
man <command>View manual/helpman ls
historyShow command historyhistory
clearClear terminal screenclear
exitExit shell sessionexit

Linux Informational Commands Cheat Sheet


🔍 1. User & Identity Info

CommandDescriptionExample
whoamiShow current usernamewhoamijohn
idShow user and group IDsid
id -uShow numeric user IDid -u1001
id -unShow username from UIDid -unjohn

🖥️ 2. Operating System Info

CommandDescriptionExample
unameShow OS nameunameLinux
uname -sShow OS name (same as above)uname -s
uname -rShow kernel release versionuname -r5.15.0-76-generic
uname -vShow kernel versionuname -v
uname -aShow all system infouname -a

💾 3. Disk Usage Info

CommandDescriptionExample
df -h ~Disk usage of home directorydf -h ~
df -hDisk usage of all mounted filesystemsdf -h
du -sh <dir>Show size of a directorydu -sh /home/john

-h makes output human-readable (e.g., GB instead of bytes)


🔄 4. Process Monitoring

CommandDescriptionExample
psShow running processes (current shell only)ps
ps -eShow all running processesps -e
topReal-time process monitortop
top -n 3Show top 3 processestop -n 3
htopEnhanced interactive process viewer (if installed)htop

🖨️ 5. Printing Strings, Variables, and Dates

CommandDescriptionExample
echo "text"Print text to terminalecho "Hello World"
echo $PATHPrint value of an environment variableecho $HOME
datePrint current date/time (default format)date
date +"%j %Y"Print day of year and yeardate +"Day %j of %Y"Day 097 of 2023
date +"%A, %j, %Y"Day name, day of year, yeardate +"%A, %j, %Y"Tuesday, 097, 2023

📚 6. Command Manuals

CommandDescriptionExample
man whoamiView manual for whoamiman whoami
man idView manual for idman id
man dfView manual for dfman df
man psView manual for psman ps
man dateView manual for dateman date
man manLearn how to use the man commandman man

📚 Getting Help for Linux Commands – A Complete Guide

When working with Linux, knowing how to find help is just as important as knowing the commands themselves. Here’s a structured approach to getting assistance when you’re stuck or curious.


🔍 1. Use the Built-in man Command

The man (manual) command is the traditional and most comprehensive way to get help in Linux.

🧾 How to Use It:

man command_name

Example:

man ls

📘 Man Page Sections:

SectionDescription
NAMEName and brief description of the command
SYNOPSISHow to use the command, including options
DESCRIPTIONDetailed explanation of what the command does
OPTIONSList of available flags or arguments
EXAMPLESCommon usage examples
SEE ALSORelated commands or documentation

📋 View All Available Man Pages:

man -k .

This lists all commands with manual pages and a short description.


📝 2. Install and Use the tldr Command

tldr provides simplified, example-based help for common commands — perfect for quick reference.

💾 Install it:

If Node.js is installed:

npm install -g tldr

🚀 Usage:

tldr ls

You’ll see concise examples like:

ls
List directory contents.

- List files one per line:
  ls -1

- List all files, including hidden ones:
  ls -a

Ideal for users who want just enough info to get the job done.


💬 3. Search Stack Overflow

Stack Overflow is a powerful community-driven Q&A platform for developers and sysadmins.

🔍 Tips for Searching:

📌 Example query:
"how to delete a file in linux" site:stackoverflow.com


🤖 4. Search Stack Exchange (Unix & Linux)

Unix & Linux Stack Exchange is ideal for deeper technical questions.

🎯 Best For:


🔍 5. Just Google It!

Sometimes, a simple web search is the fastest way to solve a problem.

✅ Tips:


📋 6. Use Course Cheat Sheets

Throughout this course, you’ll encounter cheat sheets that:


📄 7. Refer to Wikipedia’s List of Unix Commands

Wikipedia maintains a list of Unix/Linux commands: 🔗 List of Unix Commands (Wikipedia)

Includes:

Great for historical context and discovering lesser-known utilities.


🧠 Summary Table: Ways to Get Help

MethodBest ForExample
manFull, official documentationman ls
tldrQuick examples and cheatsheet-style helptldr cp
Stack OverflowProgramming-related issuesSearch “how to rename file in Linux”
Stack ExchangeAdvanced Unix/Linux topicsVisit Unix & Linux SE
GoogleFast solutions and general knowledgeSearch “Linux sort file”
Cheat SheetsQuick reference and learningProvided in this course
WikipediaOverview and history of commandsList of Unix Commands

📌 Exercise 1 - Informational Commands

In this exercise, you explored several Linux commands that provide valuable system and user information. These commands are essential for understanding your environment, troubleshooting issues, and monitoring system performance.


🔍 Overview of Commands Covered

CommandPurpose
whoamiDisplays the current user
unameShows kernel/OS info
idDisplays user and group IDs
dfShows disk space usage
psLists running processes
topReal-time view of running processes and system load
echoPrints text or variables to the terminal
dateDisplays or sets the system date and time
manDisplays manual pages for commands

🧾 Detailed Breakdown

✅ 1.1 Display Current User

whoami

✅ 1.2 Get OS Info with uname

uname

To get full system info:

uname -a

This includes:


✅ 1.3 View User Identity

id

✅ 1.4 Check Disk Space

df

For human-readable format:

df -h

✅ 1.5 View Running Processes

ps

To see all processes:

ps -e

✅ 1.6 Real-Time Process Monitoring with top

top

To exit: Press q or Ctrl + C
To limit refreshes:

top -n 10

Sorting options (while top is running):


✅ 1.7 Print Messages with echo

echo "Welcome to the Linux lab"

Output:

Welcome to the Linux lab

Use -e to interpret escape characters:

echo -e "Line one\nLine two"

Output:

Line one
Line two

Common escape characters:


✅ 1.8 Show Date and Time

date

Custom formats:

date "+%D"     # mm/dd/yy
date "+%Y-%m-%d %T"  # 2025-04-05 14:30:00

Popular format specifiers:

SpecifierMeaning
%dDay of month
%hAbbreviated month (Jan-Dec)
%mMonth number
%Y4-digit year
%TTime in HH:MM:SS
%HHour (00–23)

✅ 1.9 View Manual Pages

man ls

To list all available man pages:

man -k .

Man pages typically include:


📋 Summary Table

TaskCommand
Show current userwhoami
Show OS infouname, uname -a
Show user identityid
Show disk usagedf, df -h
List running processesps, ps -e
Monitor processes livetop, top -n 10
Print textecho, echo -e
Show date/timedate, date "+format"
View command helpman command, man -k .

💡 Tips & Best Practices


📚 Practice Exercises with Solutions

Here are the practice exercises along with hints and complete solutions to reinforce your understanding of essential Linux commands.


🔹 1. Get basic information about the operating system

💡 Hint:

Use the uname command for kernel and OS-related information.

✅ Solution:

uname -a

This will display detailed system information, including:


🔹 2. View all running processes on the system

💡 Hint:

The ps command lists running processes. Use an option to show all processes.

✅ Solution:

ps -e

This shows every process currently running on the system, not just those owned by the current user.


🔹 3. Get the table of processes and sort by memory usage

💡 Hint:

Use the top command and a keyboard shortcut to sort by memory.

✅ Solution:

top

Once inside top, press:

Shift + M

This sorts the list by memory usage, allowing you to quickly identify which processes are using the most RAM.

To exit top, press q.


🔹 4. Display the current time

💡 Hint:

Use the date command with a format specifier to show only the time.

✅ Solution:

date "+%T"

Output example:

14:25:36

Other useful formats:


🔹 5. Using one command, display the messages “Hello!” and “Goodbye!” separated by a new line

💡 Hint:

Use the echo command with the -e option to interpret escape sequences like \n.

✅ Solution:

echo -e "Hello!\nGoodbye!"

Output:

Hello!
Goodbye!

The -e flag enables interpretation of backslash escapes like \n (new line) and \t (tab).


🎯 Bonus Tips


File and Directory Navigation Commands in Linux


Introduction

This video introduces the essential Linux commands for navigating files and directories. After watching, you will be able to:

✅ Use ls to list directory contents
✅ Navigate between directories using cd
✅ Understand relative vs absolute paths
✅ Search for files using the find command


1. List Files and Directories: ls Command

Purpose

The ls (list) command is used to display the contents of a directory.

Basic Usage

Common Options

OptionDescriptionExample
-lLong format – shows permissions, owner, size, date, and namels -l
-aShow hidden files (files starting with .)ls -a
-laDetailed list including hidden filesls -la

The output from ls -l includes:


2. Show Current Working Directory: pwd

Purpose

The pwd (print working directory) command shows your current location in the file system.

Usage

pwd

Example Output:

/home/user/Documents

Useful when:


3. Change Directory: cd Command

Purpose

The cd (change directory) command lets you move between directories.

Basic Syntax

cd <directory_path>

Examples

CommandDescription
cd DocumentsMove into the Documents subdirectory
cd ..Move up one level to the parent directory
cd ~ or just cdGo to your home directory
cd /home/user/Documents/NotesMove to an absolute path
cd ./projectsMove to a relative path

Understanding Path Types

TypeDescriptionExample
Absolute PathStarts from root /, always starts with //var/log/syslog
Relative PathRelative to current working directory../images/logo.png

4. Find Files: find Command

Purpose

The find command helps you locate files and directories based on various criteria like name, type, size, etc.

Basic Syntax

find <starting_directory> <options>

Common Examples

CommandDescription
find . -name "a.txt"Find all files named a.txt in current directory (.)
find /home/user -name "*.txt"Find all .txt files in user’s home directory
find . -iname "a.txt"Case-insensitive search for a.txt
find . -type d -name "Images"Find directories named Images
find . -type fFind only files in current directory tree

Tip: The . means “start searching here” — it’s useful when you want to limit the scope of your search.


5. Summary of Key Concepts

ls – Listing Contents

pwd – Knowing Where You Are

cd – Moving Around

find – Searching Efficiently


6. Quick Reference Table

TaskCommand
List files in current directoryls
List with detailsls -l
Show hidden filesls -a
Print current directorypwd
Move into a directorycd <dir>
Move to home directorycd ~ or cd
Move up one levelcd ..
Move to absolute pathcd /path/to/dir
Find files by namefind . -name "filename"
Find files case-insensitivelyfind . -iname "filename"
Find directories onlyfind . -type d -name "dirname"

7. Final Thoughts

Mastering these navigation commands gives you control over your Linux environment. Whether you’re organizing files, troubleshooting issues, or writing scripts, understanding how to navigate the filesystem efficiently is crucial.


File and Directory Management Commands in Linux V2


1. Introduction

✅ Creating and deleting files and directories
✅ Copying and moving files and folders
✅ Managing file permissions (e.g., making a script executable)

These commands are essential for managing your system, organizing data, and working with scripts or configuration files.


2. Creating and Removing Files and Directories

A. mkdir – Make Directory

Creates a directory named test in the current location.


B. rm – Remove Files or Directories

⚠️ Warning: Use rm -r carefully — it deletes everything inside the directory recursively.


C. rmdir – Remove Empty Directories

If the folder contains files or subdirectories, this command will fail — use rm -r instead.


D. touch – Create Empty Files or Update Timestamps

Useful for testing, scripting, or resetting file timestamps.


3. Copying and Moving Files and Directories

A. cp – Copy Files or Directories

The -r option enables recursive copying of directories and their contents.


B. mv – Move or Rename Files/Directories

Unlike cp, mv does not duplicate the original — it moves or renames.


4. Managing File Permissions with chmod

A. chmod – Change File Mode (Permissions)

Common Options

OptionDescription
+rAdd read permission
+wAdd write permission
+xAdd execute permission
-rRemove read permission
-wRemove write permission
-xRemove execute permission

Example: Making a Script Executable

chmod +x my_script.sh

Now you can run the script:

./my_script.sh

5. Summary of Key Commands

TaskCommandNotes
Create a directorymkdir <dir>
Remove a filerm <file>
Remove a directory and contentsrm -r <dir>Use with caution
Remove an empty directoryrmdir <dir>Safe alternative
Create or update a filetouch <file>Sets current timestamp
Copy filescp <src> <dest>Use cp -r for directories
Move or rename filesmv <src> <dest>Also used for renaming
Change file permissionschmod +x <file>Makes a file executable

6. Final Tips


📁 Exercise 1 - Navigating Files and Directories

In this exercise, you practiced essential Linux commands for navigating the filesystem, listing directory contents, and understanding file patterns.


📍 1.1 Get the Location of the Present Working Directory

Command:

pwd

What It Does:

Example output:

/home/theia

📋 1.2 List Files and Directories in a Directory

Basic Usage:

ls

View Contents of /bin (Binary Directory):

ls /bin

Use Wildcards to Match Patterns:

🔍 All files starting with b:

ls /bin/b*

🔍 All files ending with r:

ls /bin/*r

💡 The * wildcard matches any number of characters


📄 Long Listing Format

See detailed file information:

ls -l

Includes:

Common ls Options:

OptionDescription
-aShow hidden files (those starting with .)
-dShow directories only
-hHuman-readable sizes (e.g., KB, MB)
-lLong listing format
-SSort by file size (largest first)
-tSort by modification time (newest first)
-rReverse sort order

Example: List all files (including hidden ones) in long format:

ls -la

Example: List all files in /etc with details:

ls -la /etc

This helps you explore system-wide configuration files.


✅ Summary Table

TaskCommand
Show current directorypwd
List files in current dirls
List files in /binls /bin
List files matching patternls /bin/b*, ls /bin/*r
Long list formatls -l
Show hidden filesls -a
Long list including hiddenls -la
Human-readable sizesls -lh

💡 Pro Tips


📁 Exercise 2 - Creating Files and Directories

In this exercise, you practiced using Linux commands to create directories, navigate the filesystem, and create or update files using the touch command.


✅ Summary of Commands Covered

TaskCommand
Create a directorymkdir directory_name
Change working directorycd directory_name
Move up one directory levelcd ..
Go back to home directorycd
Create an empty file or update timestamptouch filename

🧾 Step-by-Step Breakdown

🔹 2.1 Create a Directory with mkdir

mkdir scripts

Verify it was created:

ls

You should see scripts listed.


🔹 2.2 Change Working Directory with cd

Move into the scripts directory:

cd scripts

Check your current location:

pwd

Return to your home directory:

cd

Move up one level (to the parent directory):

cd ..

This is useful when navigating through nested directories.


🔹 2.3 Create an Empty File with touch

Go back to your home directory:

cd

Create a new file called myfile.txt:

touch myfile.txt

Verify the file exists:

ls

If the file already exists, touch updates its last-modified timestamp:

touch myfile.txt

To check the updated timestamp:

date -r myfile.txt

This shows the last time the file was accessed or modified.


📋 Tips & Tricks


🧠 Why These Commands Matter

These basic tools are essential for managing your workspace in Linux:


📁 Exercise 3 - Managing Files and Directories

In this exercise, you practiced essential Linux commands for searching, removing, moving, renaming, and copying files and directories — key skills for managing your system effectively.


✅ Summary of Commands Covered

TaskCommand
Search for filesfind
Remove (delete) filesrm, rm -i
Move or rename filesmv
Copy filescp

🔍 Step-by-Step Breakdown

🔹 3.1 Search for Files Using find

find /etc -name '*.txt'

🔹 3.2 Remove Files with rm

rm -i myfile.txt

After deletion, verify:

ls

⚠️ Warning: Deleted files cannot be recovered easily. Always double-check what you’re deleting.

Use without -i only when sure:

rm myfile.txt

Delete multiple files safely using confirmation:

rm -i *.txt

🔹 3.3 Move or Rename Files with mv

✏️ Rename a File:

mv users.txt user-info.txt

This renames users.txt to user-info.txt in the same directory.

Verify:

ls

📦 Move a File to Another Directory:

mv user-info.txt /tmp

Moves user-info.txt to the /tmp directory.

Verify:

ls
ls -l /tmp

💡 If the target file already exists, it will be overwritten silently — always be cautious!


🔹 3.4 Copy Files with cp

📄 Copy from One Location to Another:

cp /tmp/user-info.txt user-info.txt

This copies the file back to your current working directory.

Verify:

ls

📂 Copy Content of a System File:

cp /etc/passwd users.txt

This creates a new file users.txt containing the contents of /etc/passwd.

Check that the copy was successful:

ls
cat users.txt

You can also view the first few lines:

head users.txt

🧰 Pro Tips


🧠 Why These Commands Matter

These tools give you full control over your filesystem:

They form the foundation for automating tasks, writing scripts, and managing data efficiently.


📚 Practice Exercises – Managing Files and Directories

Here are the practice exercises with hints and solutions to help reinforce your understanding of Linux commands for navigating, creating, moving, copying, and deleting files and directories.


🔹 1. Display the contents of the /home directory

💡 Hint:

Use the ls command to list directory contents.

✅ Solution:

ls /home

This shows all user directories inside /home.


🔹 2. Ensure that you are in your home directory

💡 Hint:

Use the cd command without arguments to return to your home directory.

✅ Solution:

cd

You can verify using:

pwd

It should output something like:

/home/theia

🔹 3. Create a new directory called tmp and verify its creation

💡 Hint:

Use mkdir to create a directory and ls to confirm it exists.

✅ Solution:

mkdir tmp
ls

You should see tmp listed in the output.


🔹 4. Create a new, empty file named display.sh in the tmp directory, and verify its creation

💡 Hint:

Navigate into the tmp directory and use touch to create an empty file.

✅ Solution:

cd tmp
touch display.sh
ls

You should see display.sh listed.


🔹 5. Create a copy of display.sh, called report.sh, within the same directory

💡 Hint:

Use the cp command to make a copy of a file.

✅ Solution:

cp display.sh report.sh
ls

Now both display.sh and report.sh should be listed.


🔹 6. Move your copied file, report.sh, up one level in the directory tree to the parent directory. Verify your changes

💡 Hint:

Use mv to move the file and cd .. or ls -l ../ to check.

✅ Solution:

mv report.sh ..
ls ..

Or:

cd ..
ls

You should now see report.sh in the parent directory.


🔹 7. Delete the file display.sh

💡 Hint:

Use the rm command to delete a file. Consider using -i for confirmation (optional).

✅ Solution:

rm display.sh

To verify:

ls

The file display.sh should no longer appear.


🔹 8. List the files in /etc directory in the ascending order of their access time

💡 Hint:

Use the ls command with appropriate options to sort by access time.

✅ Solution:

ls -ltu /etc

This lists files sorted by when they were last accessed, newest first.


🔹 9. Copy the file /var/log/bootstrap.log to your current directory

💡 Hint:

Use the cp command to copy a file from its source path to the current directory.

✅ Solution:

cp /var/log/bootstrap.log .

To verify:

ls

You should see bootstrap.log in your current directory.


🧠 Bonus Tips


Great job completing these hands-on exercises! You’re now comfortable with basic file and directory management in Linux.


🔒 Security: Managing File Permissions and Ownership – Summary & Guide

In this reading, you learned how to manage file permissions and ownership in Linux — a crucial skill for protecting sensitive data and ensuring system security.


🎯 Learning Objectives Recap

By the end of this section, you should be able to:


🔐 Why File Permissions Matter

Linux is a multi-user operating system, which means multiple people can access the same machine. Without proper permissions:

That’s why permissions and ownership allow fine-grained control over who can read, write, or execute files.


👤 Types of Owners in Linux

There are three categories of users that determine permission levels:

CategoryMeaning
user (u)The owner of the file (usually the creator)
group (g)A group of users assigned to the file
other (o)Everyone else with access to the system

Each category has its own set of permissions:


👀 Viewing File Permissions

Use:

ls -l filename

Example output:

-rw-r--r-- 1 theia users 25 Dec 22 17:47 my_new_file

📘 For directories:


🔧 Changing File Permissions with chmod

You can change permissions using:

chmod [options] filename

Example: Make a file private

chmod go-r my_new_file

This removes read permission for group and others.

After running:

ls -l my_new_file

You’ll see:

-rw------- 1 theia users 24 Dec 22 18:49 my_new_file

Now only the owner can read and write to the file.

⚠️ Only the owner or root can change permissions on a file.


🛠️ Common chmod Syntax Options

CommandAction
chmod u+x file.shAdd execute permission for the user
chmod go-w file.txtRemove write permission for group and others
chmod 755 file.shSet numeric permissions (see below)

Numeric Permission Notation

Each permission level has a number value:

Sum them to get numeric values:

PermissionValue
rwx7
rw-6
r-x5
r--4

Example:

chmod 600 secret.txt

Only the owner has read and write access.


📁 Executable Files and Shell Scripts

To make a shell script executable:

  1. Add a shebang line at the top:
    #!/bin/bash
  2. Give it execute permission:
    chmod +x script.sh
  3. Run it:
    ./script.sh

This tells the OS that the file is a program written in Bash (or another interpreter).


✅ Summary Table

ConceptDescription
User (u)Owner of the file
Group (g)Group of users who share ownership
Other (o)All other users
Permissionsr = read, w = write, x = execute
View Permissionsls -l
Change Permissionschmod
Make Privatechmod go-rwx filename
Numeric Modechmod 600 filename
Directoriesr = list, w = modify contents, x = enter

💡 Pro Tips


You’re now equipped with the knowledge to secure your files, control access, and protect sensitive data in a Linux environment.


🛠️ Exercise 1 - Viewing and Modifying File Access Permissions

In this exercise, you learned how to view and modify file permissions in Linux using the ls -l and chmod commands. Understanding and managing permissions is essential for maintaining system security and controlling access to your files.


📁 1.1 View File Access Permissions

🔧 Steps:

  1. Navigate to your project directory:

    cd /home/project
  2. Download the required file:

    wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-LX0117EN-SkillsNetwork/labs/module%201/usdoi.txt
  3. View the file’s permissions:

    ls -l usdoi.txt

✅ Sample Output:

-rw-r--r-- 1 theia theia 8121 May 31 16:45 usdoi.txt

📝 Breakdown of Permission String: -rw-r--r--

PartMeaning
-It’s a regular file (use d for directories)
rw-User (owner) has read and write
r--Group has only read
r--Others have only read

🔐 1.2 Change File Access Permissions with chmod

The chmod command allows you to modify who can read, write, or execute a file.

🔧 Syntax:

chmod [who][operator][permission] filename
ComponentValues
whou = user, g = group, o = others, a = all
operator+ = add, - = remove, = = set exactly
permissionr = read, w = write, x = execute

🔍 Example Commands

❌ Remove read permission for all users:

chmod -r usdoi.txt

Verify:

ls -l usdoi.txt

You’ll see something like:

--w------- 1 theia theia 8121 May 31 16:45 usdoi.txt

✅ Restore read permission for all users:

chmod +r usdoi.txt

Verify:

ls -l usdoi.txt

You should return to:

-rw-r--r-- 1 theia theia 8121 May 31 16:45 usdoi.txt

🚫 Remove read permission only for “other”:

chmod o-r usdoi.txt

Verify:

ls -l usdoi.txt

Now output will be:

-rw-r----- 1 theia theia 8121 May 31 16:45 usdoi.txt

Only user and group can read the file now.


🧠 Summary Table

TaskCommand
View file permissionsls -l filename
Remove read from allchmod -r filename
Add read to allchmod +r filename
Remove read from otherschmod o-r filename
Add execute to userchmod u+x filename
Set exact permissions (e.g., rw-------)chmod 600 filename

💡 Pro Tips


Great job completing this exercise! You’re now able to view and manage file permissions — an essential skill for working securely in Linux.


📁 Exercise 2 - Understanding Directory Access Permissions

In this exercise, you explored how directory permissions in Linux work and how they differ from file permissions. You learned that execute (x) permission is required to enter a directory, and write (w) permission is needed to create or delete files inside it.


🔍 Summary of What You Learned

PermissionMeaning for Directories
r (read)Allows listing contents with ls
w (write)Allows adding/removing files
x (execute)Allows entering the directory using cd

⚠️ Even if you have write access, you can’t modify contents without execute permission!


🧾 Step-by-Step Breakdown

🔹 2.1 View Default Directory Access Permissions

Create a new directory:

cd /home/project
mkdir test

Check its permissions:

ls -l

Output example:

drwxr-sr-x 2 theia users 4096 May 15 14:06 test

You verified that:

Commands used:

cd test
mkdir test2
cd ..

💡 The s in group permissions is a special flag called setgid — it ensures new files inherit the group of the parent directory.


🔹 2.2 Remove User Execute Permissions

Remove execute permission for owner:

chmod u-x test

Now try:

cd test

❌ Output:

bash: cd: test: Permission denied

Even though you still have read and write permissions, you can’t enter the directory without execute permission.

Try listing contents:

ls -l test

✅ Works — because you still have read permission.

Try creating a subdirectory:

mkdir test/test3

❌ Fails — because write requires execute.


🔁 Restore Permissions

Add back execute:

chmod u+x test

Remove write:

chmod u-w test

Check current permissions:

ls -l

Now try:

cd test
mkdir test_again

❌ Output:

mkdir: cannot create directory ‘test_again’: Permission denied

You can enter the directory (thanks to x), but you can’t modify it (because you don’t have w).


🧠 Key Takeaways

ScenarioRequired Permission
List contents (ls)r
Enter directory (cd)x
Create/delete filesw + x
Rename or move filesw + x in both source and target directories

🧩 Think of x as a key to open a door — you need it before you can do anything useful inside a directory.


✅ Summary Table

CommandEffect
ls -lShow directory permissions
chmod u+x dirAllow user to enter directory
chmod u-w dirPrevent user from modifying directory contents
cd dirRequires execute (x) permission
ls dirRequires read (r) permission
mkdir dir/subdirRequires write (w) + execute (x) permissions on dir

You’ve now mastered how directory permissions control access differently than file permissions — an essential concept for securing and managing your Linux system effectively.


🛠️ Practice Exercises – File and Directory Permissions

Here are the practice exercises with hints and full solutions to help you reinforce your understanding of Linux file and directory permissions.


🔹 1. List the permissions set for the file usdoi.txt

💡 Hint:

Use the ls -l command to view file permissions.

✅ Solution:

ls -l usdoi.txt

Example output:

-rw-r--r-- 1 theia users 8121 May 31 16:45 usdoi.txt

This shows that:


🔹 2. Revoke the write permission on usdoi.txt for the user, and verify

💡 Hint:

Use chmod u-w to remove write access for the user.

✅ Solution:

chmod u-w usdoi.txt
ls -l usdoi.txt

New output:

-r--r--r-- 1 theia users 8121 May 31 16:45 usdoi.txt

The user (owner) no longer has write permission.


🔹 3. What happens if you try to delete usdoi.txt after revoking write permissions?

💡 Hint:

You don’t need write permission to delete a file — but you do need write permission in the directory it’s in.

✅ Solution:

Try deleting:

rm usdoi.txt

✅ It works!
Even though you removed write permission on the file, you can still delete it because:

🔍 Note: If you didn’t own the file, you could still delete it as long as:

  • You had write permission in the directory
  • You didn’t own the file

🔹 4. Create a new directory called tmp_dir in your home directory

💡 Hint:

Use the mkdir command.

✅ Solution:

cd ~
mkdir tmp_dir

Now you have a new directory in your home folder.


🔹 5. View the permissions of the newly created directory tmp_dir

💡 Hint:

Use ls -l again to see directory permissions.

✅ Solution:

ls -l

Output will include something like:

drwxr-xr-x 2 theia users 4096 Apr 5 10:00 tmp_dir

This means:


🔹 6. Revoke the user write permission for tmp_dir

💡 Hint:

Use chmod u-w on the directory.

✅ Solution:

chmod u-w tmp_dir
ls -l

New output:

dr-xr-xr-x 2 theia users 4096 Apr 5 10:00 tmp_dir

User now only has execute and read — not write.


🔹 7. Check whether you can create a subdirectory sub_dir inside tmp_dir

💡 Hint:

Use mkdir to attempt creating a subdirectory.

✅ Solution 1:

mkdir tmp_dir/sub_dir

❌ Output:

mkdir: cannot create directory ‘tmp_dir/sub_dir’: Permission denied

✅ Solution 2 Explanation:

Even though you have execute (x) permission on tmp_dir, which allows you to enter the directory, you don’t have write (w) permission — so you can’t modify its contents (like creating or deleting files or directories).


🧠 Summary Table

TaskCommand
View file permissionsls -l filename
Remove write from userchmod u-w filename
Delete a filerm filename (requires write in directory)
Create a directorymkdir dirname
View directory permissionsls -l
Remove write from directorychmod u-w dirname
Create subdirectorymkdir dirname/subdir (fails without w + x)

Great job working through these permission exercises! You’re building strong skills in managing file access control, user permissions, and directory behavior in Linux.


Viewing File Content in Linux


1. Introduction

✅ Displaying full or partial contents of a file
✅ Navigating large files page-by-page
✅ Counting lines, words, and characters

These tools are especially useful when working with log files, scripts, configuration files, and other text-based data.


2. Commands to View File Contents

A. cat – Concatenate and Print Entire File

Outputs all lines from the file numbers.txt, from line 0 to 99 in this example.

⚠️ Not ideal for long files — output may scroll off-screen quickly.


B. more – View File One Page at a Time

Ideal for reading long files without overwhelming the terminal.


C. head – View First Few Lines of a File

Useful for checking headers, logs, or sample data quickly.


D. tail – View Last Few Lines of a File


3. Command to Analyze File Content: wc

A. wc – Word Count

Output:

7 7 28 pets.txt

The character count is higher than expected because wc counts newline characters (\n) as well.


B. Options for Specific Counts

OptionDescriptionExample
-lCount only lineswc -l pets.txt7 pets.txt
-wCount only wordswc -w pets.txt7 pets.txt
-cCount only characters (including newlines)wc -c pets.txt28 pets.txt

These options let you extract specific metrics without extra parsing.


4. Summary Table

CommandPurposeExampleOutput Sample
catView entire filecat numbers.txtAll lines from 0 to 99
moreView file page-by-pagemore numbers.txtScrollable output
headView first 10 lineshead numbers.txtLines 0–9
head -n XView first X lineshead -n 3 numbers.txtLines 0–2
tailView last 10 linestail numbers.txtLines 90–99
tail -n XView last X linestail -n 3 numbers.txtLines 97–99
wcCount lines, words, charswc pets.txt7 7 28 pets.txt
wc -lCount only lineswc -l pets.txt7 pets.txt
wc -wCount only wordswc -w pets.txt7 pets.txt
wc -cCount only characterswc -c pets.txt28 pets.txt

5. Final Tips


Useful Commands for Wrangling Text Files in Linux


1. Introduction

✅ Sorting lines alphabetically
✅ Removing duplicates
✅ Searching for patterns
✅ Extracting parts of lines
✅ Merging lines from multiple files

These tools are essential for working with log files, CSV data, configuration files, and more.


2. Sorting File Content: sort Command

Purpose

Sort the lines of a file alphabetically or numerically.

Basic Syntax

sort <filename>

Examples

Tip: Use sort -n for numeric sorting if your file contains numbers.


3. Removing Duplicate Lines: uniq Command

Purpose

Filter out consecutive duplicate lines in a file.

Basic Syntax

uniq <filename>

Example

Given this content in pets.txt:

cat
dog
dog
cat

Running:

uniq pets.txt

Output:

cat
dog
cat

Note: uniq only removes duplicates that appear one after another. To remove all duplicates regardless of position, first use sort, then uniq:

sort pets.txt | uniq

4. Searching for Patterns: grep Command

Purpose

Search for lines containing a specific pattern (e.g., word, phrase, regular expression).

Basic Syntax

grep "pattern" <filename>

Examples

grep supports regular expressions for advanced searches:

grep "^C" people.txt   # Find names starting with 'C'

5. Extracting Parts of Lines: cut Command

Purpose

Extract specific characters or fields from each line of a file.

Basic Syntax

cut [options] <filename>

A. Character-Based Extraction

B. Field-Based Extraction

Use -d to define a delimiter and -f to select a field.

You can also extract multiple fields:

cut -d',' -f1,3 csvfile.csv

6. Merging Lines from Multiple Files: paste Command

Purpose

Combine lines from multiple files side by side, similar to columns in a table.

Basic Syntax

paste <file1> <file2> <file3>

Example

You have three files:

Run:

paste first.txt last.txt yob.txt

Output:

Alan    Turing    1912
Charles Babbage   1791
Dennis  Ritchie   1941

By default, paste uses tab as the delimiter.

Custom Delimiter

To use a comma instead:

paste -d',' first.txt last.txt yob.txt

Output:

Alan,Turing,1912
Charles,Babbage,1791
Dennis,Ritchie,1941

7. Summary Table

CommandPurposeExample
sortSort lines alphabetically/numericallysort pets.txt
sort -rReverse sortsort -r pets.txt
uniqRemove consecutive duplicate linesuniq pets.txt
grep "pattern"Print lines matching a patterngrep "ch" people.txt
grep -iCase-insensitive searchgrep -i "ch" people.txt
cut -cX-YExtract characters from X to Ycut -c2-9 people.txt
cut -d' ' -f2Extract second field using space as delimitercut -d' ' -f2 people.txt
pasteMerge lines from multiple filespaste first.txt last.txt yob.txt
paste -d','Merge with custom delimiterpaste -d',' first.txt last.txt yob.txt

8. Final Tips


📄 Exercise 1 - Viewing File Contents with cat, more, and less

In this exercise, you learned how to view and navigate file contents in the terminal using three essential Linux commands:

These tools are especially useful when working with shell scripts, logs, configuration files, and other text-based data.


🔧 Step-by-Step Breakdown

🏁 Start by navigating to your home directory:

cd ~

🔍 Check what files exist:

ls

You should see a file named entrypoint.sh. .sh is the extension used for shell scripts, which are executable text files that contain Bash commands.


✅ 1.1 View File Content with cat

Command:

cat entrypoint.sh

What It Does:

⚠️ If the file is longer than your terminal window, you’ll only see the last part — it scrolls past too quickly to read everything.

💡 Use Cases:


✅ 1.2 View File Content with more

Command:

more entrypoint.sh

What It Does:

🔍 Useful Info:

The first line:

#!/bin/bash

is called a shebang — it tells the system to use /bin/bash to interpret the script.

📌 You’ll learn more about writing shell scripts later in the course.

💡 Use Cases:


✅ 1.3 Scroll Through File Content with less

Command:

less entrypoint.sh

What It Does:

🆕 Why less Is Better Than more:


📋 Summary Table

CommandScrolling DirectionInteractiveExits AutomaticallyBest For
catAll at onceNoYesSmall files, scripting
moreForward onlyLimitedYesPaging through files
lessBoth forward/backwardFullNoDetailed inspection, logs

🧠 Tips & Tricks


Great job completing this exercise! You now know how to choose the best tool depending on the size and complexity of the file you’re viewing.


📄 Exercise 2 - Viewing Text File Contents

Using head and tail to View File Content

In this exercise, you learned how to inspect specific parts of a text file using two powerful Linux commands:

These tools are especially useful for:


🧾 Step-by-Step Instructions

🔧 Download and Navigate to Your Project Directory:

cd /home/project
wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DB0250EN-SkillsNetwork/labs/Bash%20Scripting/usdoi.txt

Verify the file was downloaded:

ls

You should see usdoi.txt listed.


✅ 2.1 Display the First N Lines with head

Show the first 10 lines (default):

head usdoi.txt

This is helpful when viewing large documents like logs or configuration files where the most important info may be at the top.

Show only the first 3 lines:

head -3 usdoi.txt

Example output:

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another...

💡 Use head to quickly preview files without opening the entire contents.


✅ 2.2 Display the Last N Lines with tail

Show the last 10 lines (default):

tail usdoi.txt

Useful for checking the end of logs or files where recent changes are appended.

Show only the last 2 lines:

tail -2 usdoi.txt

Example output:

...and that government of the people, by the people, for the people shall not perish from the earth.

🚀 Pro Tip: Use tail -f to follow a log file in real time:

tail -f /var/log/syslog

📋 Summary Table

CommandDescriptionExample
headDisplays the first 10 lines of a filehead filename
head -NDisplays the first N lineshead -3 filename
tailDisplays the last 10 lines of a filetail filename
tail -NDisplays the last N linestail -2 filename
tail -fFollows the end of a file in real timetail -f /var/log/syslog

🧠 Why These Commands Matter


Great work! You now know how to quickly inspect large text files, which is essential for system administration, scripting, and data analysis.


📊 Exercise 3 - Getting Basic Text File Stats with wc

In this exercise, you learned how to use the wc (word count) command to get basic statistics about a text file — including the number of lines, words, and characters.

This is especially useful when:


🔧 Step-by-Step Breakdown

Start by navigating to your project directory and using wc:

cd /home/project
wc usdoi.txt

Example Output:

     21     268    1654 usdoi.txt

The output shows:

  1. Number of lines
  2. Number of words
  3. Number of characters
  4. File name

✅ View Specific Stats

🔢 Count Lines Only:

wc -l usdoi.txt

Useful for checking how many entries are in a list or log file.


📝 Count Words Only:

wc -w usdoi.txt

Great for content analysis or verifying document length.


🔤 Count Characters Only:

wc -c usdoi.txt

Tells you the total byte size of the file — useful for storage and transmission planning.

💡 Note: wc -c counts bytes, not just visible characters — so whitespace and punctuation are included.


📋 Summary Table

CommandOutput
wc filenameLines, words, characters
wc -l filenameNumber of lines
wc -w filenameNumber of words
wc -c filenameNumber of bytes (characters)

🧠 Why wc Is Useful


You’re doing great! With these tools, you can now analyze text files efficiently and extract meaningful insights from their content.

🧹 Exercise 4 - Basic Text Wrangling: Sorting Lines and Dropping Duplicates

In this exercise, you learned how to clean up and organize text data using two powerful Linux utilities:

These tools are essential for:


🔧 Step-by-Step Breakdown

✅ 4.1 Sort Lines Alphanumerically with sort

Display the lines of usdoi.txt sorted alphanumerically:

sort usdoi.txt

This command rearranges all the lines in alphabetical order (A–Z), making it easier to scan or analyze content.

Sort in reverse order (Z–A):

sort -r usdoi.txt

💡 This is useful when you want to see the “end” of an alphabetized list first — like viewing the latest entries in a log.


✅ 4.2 Remove Consecutive Duplicate Lines with uniq

First, download a new file:

wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-LX0117EN-SkillsNetwork/labs/module%201/zoo.txt

View the contents:

cat zoo.txt

You’ll notice some repeated animal names, especially zebra.

Remove consecutive duplicates:

uniq zoo.txt

This removes only lines that appear one after another, so:

zebra
zebra
lion
tiger
zebra

Becomes:

zebra
lion
tiger
zebra

Only the first two zebras are removed as duplicates — the last one stays because it’s not directly after another zebra.


📋 Summary Table

| Command | Description | | ------------------ | -------------------------------------- | -------------------------------------------- | | sort filename | Sort lines alphabetically | | sort -r filename | Sort lines in reverse order | | uniq filename | Remove consecutive duplicate lines | | sort file | uniq | Sort then remove all duplicates (if grouped) |


🧠 Pro Tips


🛠️ Real-World Use Cases

| Task | Command | | --------------------------------- | ---------------------------- | ------------------------ | -------- | -------- | ----------- | | Clean up a messy list of emails | sort emails.txt | uniq > clean_emails.txt | | Count unique IP addresses in logs | cut -d' ' -f1 access.log | sort | uniq -c | | Find most frequently visited URLs | awk '{print $7}' access.log | sort | uniq -c | sort -nr | head -n 10 |


Great job mastering these basic but powerful text processing tools! You’re now equipped to organize, clean, and analyze textual data efficiently in Linux.

🧩 Exercise 5 - Basic Text Wrangling: Extracting Lines and Fields

In this exercise, you learned how to filter lines using patterns with grep and extract specific parts of text using the cut command.

These tools are essential for:


🔍 Step-by-Step Breakdown

✅ 5.1 Extract Lines Matching a Pattern with grep

grep people usdoi.txt

This shows only the lines where the word people appears.

grep -n people usdoi.txt

Count how many lines contain the pattern:

grep -c people usdoi.txt

Ignore case (match both “People” and “people”):

grep -i people usdoi.txt

Show lines that do not contain the pattern:

grep -v login /etc/passwd

Useful for filtering out system-generated accounts from /etc/passwd.

Match only whole words:

grep -w people usdoi.txt

Prevents partial matches like peoples or unpeople.


✅ 5.2 Extract Fields from Lines Using cut

View first two characters of each line in zoo.txt:

cut -c -2 zoo.txt

View text starting from the second character:

cut -c 2- zoo.txt

These options extract by character position, useful for fixed-width formats.


📥 Work with Delimited Files (e.g., CSV)

Download and view the file:

wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-LX0117EN-SkillsNetwork/labs/v4_new_content/labs/names_and_numbers.csv
cat names_and_numbers.csv

Sample content:

Name,Phone
Alice,555-1234
Bob,555-5678
Charlie,555-9012

Extract just the phone numbers (second field):

cut -d "," -f2 names_and_numbers.csv

Output:

Phone
555-1234
555-5678
555-9012

You can also extract multiple fields:

cut -d "," -f1,3 names_and_numbers.csv

Returns fields 1 and 3 — useful when skipping unnecessary columns.


📋 Summary Table

TaskCommand
Find lines containing a wordgrep pattern file
Show line numbersgrep -n pattern file
Count matchesgrep -c pattern file
Case-insensitive searchgrep -i pattern file
Invert match (not containing)grep -v pattern file
Match whole word onlygrep -w pattern file
Extract characters by positioncut -c START-END file
Extract fields by delimitercut -d "DELIM" -f FIELD_NUMBERS file

🧠 Why These Tools Matter

ToolUse Case
grepSearch, filter, and count patterns in text
cutExtract specific parts of text based on position or delimiters

They’re often used together in pipelines:

grep "New York" contacts.csv | cut -d "," -f2

This finds all entries for New York and extracts their phone numbers.


🧩 Exercise 6 - Basic Text Wrangling: Merging Lines as Fields

In this exercise, you learned how to use the paste command to merge lines from multiple files side-by-side, like combining columns in a spreadsheet.

This is especially useful when:


🔧 Step-by-Step Breakdown

✅ Download an additional file:

wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-LX0117EN-SkillsNetwork/labs/module%201/zoo_ages.txt

You already have zoo.txt, which contains animal names. Now zoo_ages.txt has corresponding age data.

✅ Merge both files line-by-line using paste:

paste zoo.txt zoo_ages.txt

By default, paste uses a Tab (\t) character to separate merged fields.

Example Output:

lion	5
tiger	4
zebra	6
elephant	10

This makes it easy to combine related data into a single view.


✅ Change the Delimiter to Comma (,) for CSV-like Output:

paste -d "," zoo.txt zoo_ages.txt

Now the output looks like:

lion,5
tiger,4
zebra,6
elephant,10

💡 This is useful for creating CSV files or preparing data for scripts and databases.

You can also use other delimiters like space, colon, or semicolon:

paste -d " " zoo.txt zoo_ages.txt   # Space
paste -d ":" zoo.txt zoo_ages.txt  # Colon

📋 Summary Table

CommandDescription
paste file1 file2Merge two files line-by-line using Tab delimiter
paste -d "," file1 file2Merge using comma as delimiter
paste -s file.txtPaste all lines of a file into one line
paste -d ":" file1 file2 > merged.csvSave merged output to a new file

🧠 Why paste Is Useful

Use CaseExample
Combine logs from different sourcespaste access.log user_agents.log
Build CSV files from parallel datapaste -d "," names.csv ages.csv > people.csv
Align configuration valuesMatch hostnames with IPs
Create input for scriptsGenerate formatted input for another tool

🛠️ Try It Out – Real-World Examples

Combine Names and Ages into One File:

paste -d "," zoo.txt zoo_ages.txt > animals.csv

Creates a new file animals.csv that’s ready for import into Excel or a database.

Merge Multiple Files:

paste names.txt emails.txt phones.txt

Merges three files — one per column — ideal for building contact lists.


🛠️ Practice Exercises – Text Processing in Linux

These hands-on exercises help reinforce your knowledge of file inspection, searching, and text manipulation using essential Linux commands like wc, grep, head, tail, cut, and more.


🔧 Before You Begin

Make sure you’re in your home directory:

cd ~
pwd

📝 Practice Exercise Solutions

1. Display the number of lines in /etc/passwd

✅ Solution:

wc -l /etc/passwd

This shows how many user accounts exist on the system (each line in /etc/passwd represents a user).


2. Display lines containing “not installed” in /var/log/bootstrap.log

✅ Solution:

grep "not installed" /var/log/bootstrap.log

This helps identify packages or services that failed to install during system boot.


3. Find websites with “org” in them from top-sites.txt

First, download the file:

wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DB0250EN-SkillsNetwork/labs/Bash%20Scripting/top-sites.txt

✅ Use grep to search for “org”:

grep "org" top-sites.txt

This lists all URLs or domains that include “org”.

🔄 Alternative solution using case-insensitive match:

grep -i "org" top-sites.txt

Useful if you want to catch both “org” and “ORG”, etc.


4. Print the first 7 lines of top-sites.txt

✅ Solution:

head -7 top-sites.txt

This gives a quick preview of the top sites list.


5. Print the last 7 lines of top-sites.txt

✅ Solution:

tail -7 top-sites.txt

Handy when you’re interested in newer entries at the end of a list or log file.


6. Print the first three characters of each line from top-sites.txt

✅ Solution:

cut -c -3 top-sites.txt

This extracts only the first 3 characters from every line — useful for fixed-width data or codes.


7. Extract and view only the names from names_and_numbers.csv

Assuming the file already exists:

cat names_and_numbers.csv

✅ Solution:

cut -d "," -f1 names_and_numbers.csv

You can also skip the header if needed:

tail -n +2 names_and_numbers.csv | cut -d "," -f1

📋 Summary Table: Commands Used

TaskCommand
Count lines in a filewc -l filename
Search for text in a filegrep "pattern" filename
Print first N lineshead -N filename
Print last N linestail -N filename
Extract character rangecut -c START-END filename
Extract by delimitercut -d "DELIM" -f FIELD_NUMBERS filename

🧠 Why These Skills Matter

You now have the tools to:

These are foundational skills for scripting, system administration, and data analysis in Linux.


Exercise 7 – Combining Commands with Pipes and Redirection

In this exercise, you’ll learn how to:

These skills are essential for:


🔧 What is Piping?

The pipe operator (|) takes the output of one command and feeds it as input to another.

This lets you chain together small tools to build complex operations.

Example:

ls -l | grep "Jan" | wc -l

This pipeline:

  1. Lists all files (ls -l)
  2. Filters only those modified in January (grep "Jan")
  3. Counts them (wc -l)

📥 Input and Output Redirection

You can also control where input comes from and where output goes using:

OperatorPurposeExample
>Redirect output to a file (overwrites)ls > files.txt
>>Append output to a fileecho "New line" >> files.txt
<Redirect input from a filesort < names.txt

Example:

grep "error" /var/log/syslog > errors.txt

Saves all lines containing “error” from the system log into a new file.


💡 Hands-On Practice

Let’s go through some guided examples.

✅ 1. Chain grep, sort, and uniq to Analyze Log Data

Find unique IP addresses in an access log:

grep "Failed password" /var/log/auth.log | awk '{print $9}' | sort | uniq

You’ll learn about awk soon — it’s a powerful text processing tool.


✅ 2. Save Command Output to a File

Save your list of running processes to a file:

ps -e > process_list.txt

Now view it:

cat process_list.txt

✅ 3. Count Words in a File Using a Pipeline

Count how many times each word appears in usdoi.txt:

tr ' ' '\n' < usdoi.txt | sort | uniq -c | sort -nr

What this does:


✅ 4. View Command Output One Page at a Time

Sometimes output fills your screen. Use less to page through it:

history | less

Use ↑ ↓ keys to scroll, and press q to quit.


📋 Summary Table: Pipes & Redirection

| Task | Command | | ------------------------------ | --------------------- | --------- | | Pipe output to another command | command1 | command2 | | Redirect output to a file | command > file.txt | | Append output to a file | command >> file.txt | | Read input from a file | command < file.txt |


🧠 Why This Matters

With pipes and redirection, you can:


🎉 Summary – Great Job Completing the Lab!

You’ve just gained hands-on experience with some of the most essential Linux text processing and file inspection tools. These skills are fundamental for working efficiently in a Linux environment — whether you’re managing logs, analyzing data, or writing shell scripts.


🔍 What You Learned

Here’s a quick recap of the core commands and skills you practiced:

SkillCommand(s) Used
Viewing file contentscat, more, less
Inspecting start/end of fileshead, tail
Count lines, words, characterswc
Sort and deduplicate linessort, uniq
Search for patterns in filesgrep
Extract specific fields or characterscut
Merge files line-by-linepaste

💡 Why This Matters

These tools form the foundation of text-based data manipulation in Linux:


🧠 Pro Tip: Combine Commands with Pipes!

Now that you know these individual tools, try combining them using the pipe (|) operator:

grep "error" /var/log/syslog | wc -l

Counts how many error messages are in the system log.

Or:

cat top-sites.txt | tail -10 | grep "org" | sort

Gets the last 10 sites, filters for “org”, and sorts alphabetically.


Networking Commands in Linux


1. Introduction

This video introduces essential Linux networking commands that help you:

✅ View your network configuration
✅ Test connectivity to remote servers
✅ Retrieve data from URLs

These tools are invaluable for troubleshooting, automation, and interacting with web services.


2. hostname – Get or Set the Host Name

Purpose

Displays or sets the hostname of the machine — a unique identifier used on the network.

Basic Usage

hostname

Output:

my-linux-machine.local

Options

OptionDescription
hostname -sShow short hostname (without domain suffix)
hostname -iShow IP address associated with the host

3. ifconfig – Interface Configuration

Purpose

Displays or configures network interfaces such as Ethernet (eth0) or Wi-Fi (wlan0).

⚠️ Note: ifconfig is deprecated in many modern Linux distros; use ip addr instead.

Basic Usage

ifconfig

Shows detailed information about all active interfaces including:

Example

ifconfig eth0

Shows details only for the Ethernet interface named eth0.


4. ping – Test Network Connectivity

Purpose

Tests whether a host or IP address is reachable by sending ICMP echo requests.

Basic Syntax

ping <hostname_or_ip>

Example

ping google.com

Output:

PING google.com (142.251.41.78): 56 data bytes
64 bytes from 142.251.41.78: icmp_seq=0 ttl=119 time=10.4 ms
...

Useful Options

OptionDescription
ping -c <count>Send a specific number of packets then stop
ping -i <seconds>Interval between packets (in seconds)

Example:

ping -c 5 google.com

Returns 5 ping results and summary statistics:


5. curl – Transfer Data from or to a URL

Purpose

A powerful command-line tool for transferring data using various protocols like HTTP, HTTPS, FTP, etc.

Basic Syntax

curl <url>

Examples

Common Uses


6. wget – Retrieve Files from Web URLs

Purpose

Downloads files from the web recursively and supports resuming broken downloads.

Basic Syntax

wget <url>

Example

Download a test file from W3.org:

wget https://www.w3.org/TR/2002/REC-xml-20021104/ISO-Latin-1-encoding.txt

Output Includes

Useful Options

OptionDescription
-O <filename>Specify custom output filename
-rRecursive download (mirror websites)
-cResume broken download

Example:

wget -O iso.txt https://www.w3.org/TR/2002/REC-xml-20021104/ISO-Latin-1-encoding.txt

7. Summary Table of Networking Commands

CommandPurposeExample
hostnameDisplay or set hostnamehostnamemy-linux-machine.local
hostname -sShow short hostnamehostname -smy-linux-machine
hostname -iShow IP addresshostname -i192.168.1.100
ifconfigShow network interface infoifconfig or ifconfig eth0
pingTest connectivity to a hostping google.com
ping -c 5 google.comPing 5 times and exitping -c 5 google.com
curlTransfer data from or to a URLcurl http://example.com
curl -o file.txt http://example.comSave output to a fileSaves content to file.txt
wgetDownload files from a URLwget http://example.com/file.txt
wget -O custom_name.txt urlDownload and rename filewget -O data.txt http://example.com/data

8. Final Tips


9. Bonus: Modern Alternative to ifconfigip Command

While ifconfig is widely known, it’s being replaced by the more powerful ip command suite:

Taskip Equivalent
Show IP addressesip addr show or ip a
Show routing tableip route show or ip r
Bring up/down an interfacesudo ip link set eth0 up

🌐 A Brief Introduction to Networking – Summary & Highlights

Great job reading through this foundational networking guide! This optional but valuable reading introduced you to core concepts in computer networking, helping you understand how computers communicate, share resources, and connect across networks like the Internet.


🎯 Learning Objectives Recap

After completing this reading, you are now able to:

Describe computer networks, network resources, and network nodes
Explain the roles of hosts, clients, and servers
Understand what packets and pings are
Differentiate between URLs and IP addresses


🧩 Key Concepts Explained

🔹 Computer Networks

💡 The internet is essentially a network of computer networks.


🔁 Hosts, Clients, and Servers

TermDescription
HostAny device on a network with an IP address. Can act as a server or client
ClientRequests services or data from a server
ServerProvides services or data to clients (e.g., web servers, email servers)

💡 Many devices can switch roles — acting as both client and server when needed.


📦 Packets and Pings

What Is a Network Packet?

What Is ping?

Example command:

ping google.com

🌍 URLs and IP Addresses

What Is an IP Address?

💡 When you use ping, it uses IP addresses to send and receive packets.


What Is a URL?

URL Format:

protocol://hostname/path

Example:

https://en.wikipedia.org/wiki/URL

Breakdown:

📌 URLs make it easier for humans to access resources without needing to remember complex IP addresses.


🧠 Why These Concepts Matter

Understanding these basics helps you:


✅ Summary Table

ConceptDescription
Computer NetworkInterconnected computers sharing resources
Network ResourceAnything identifiable and accessible via a network (e.g., files, printers)
Network NodeAny device participating in the network (computers, routers, etc.)
HostA device that can be a client or server
ClientRequests data or services from a server
ServerProvides data or services to clients
PacketUnit of data containing control info + payload
PingTests network connectivity by sending echo requests
IP AddressUnique identifier for a device on a network
URLHuman-readable address pointing to a web resource

🧾 Exercise 1 – View Configuration Info About Your Network

In this exercise, you learned how to view your system’s network configuration, including:

This is essential for understanding how your machine connects to the network and communicates with other systems.


🔍 Overview of What You Learned

TaskCommand
View system hostnamehostname
View system IP addresshostname -i
Show all network interfacesip a or ip addr
Show info about a specific interface (e.g., eth0)ip addr show eth0

✅ Step-by-Step Breakdown

🔹 1.1 Display Your System’s Hostname and IP Address

View the current hostname:

hostname

Example output:

theia-2c65847f

The hostname helps identify your machine on a network — especially useful in server environments.

View the system’s IP address:

hostname -i

Example output:

172.17.0.2

💡 This shows the IPv4 address associated with your host.


🔹 1.2 Display Network Interface Configuration

Before running the ip command, you installed the iproute2 package:

Update and install:

sudo apt update
sudo apt install iproute2

Now you can use the powerful ip command.

Show all network interfaces:

ip a

or

ip addr

This displays information like:

Example output line:

inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0

Here, 172.17.0.2 is your IPv4 address.

Show configuration for a specific interface (like eth0):

ip addr show eth0

📌 eth0 is typically the primary Ethernet interface used to connect to the network.

You’ll see:


📋 Summary Table: Useful Commands

PurposeCommand
View system hostnamehostname
View system IP addresshostname -i
List all network interfacesip a or ip addr
View specific interface (e.g., eth0)ip addr show eth0

🧠 Why These Tools Matter

Understanding your network configuration helps with:

The ip command is a modern replacement for older tools like ifconfig, and it offers more flexibility and control.


🛠️ Real-World Use Cases

TaskCommand
Check if network is upip link show eth0
Find your public IP (from terminal)curl ifconfig.me
Monitor interface changesip monitor
Bring an interface up/downsudo ip link set eth0 up / sudo ip link set eth0 down

🧪 Exercise 2 – Test Network Connectivity with ping

In this exercise, you learned how to use the ping command to test whether your system can successfully communicate with another device or website over the network.

This is a fundamental tool for:


🔍 Overview of What You Learned

TaskCommand
Ping a host continuouslyping www.google.com
Ping a host a specific number of timesping -c 5 www.google.com

✅ Step-by-Step Breakdown

🔹 2.1 Test Connectivity to a Host Using ping

Ping Google continuously:

ping www.google.com

You’ll see output like:

64 bytes from 142.251.42.78: icmp_seq=1 ttl=115 time=15.3 ms
64 bytes from 142.251.42.78: icmp_seq=2 ttl=115 time=14.9 ms
...

Each line shows:

⚠️ To stop the ping process, press Ctrl + C


Ping a Host a Specific Number of Times

To limit the number of packets sent, use the -c option:

ping -c 5 www.google.com

This sends exactly 5 packets, then stops automatically.

Useful for:


📋 Summary Table

CommandDescription
ping hostnameTests if a remote host is reachable
ping -c N hostnamePings the host exactly N times
ping -c 5 google.comSends 5 packets to google.com and stops

🧠 Why This Matters

Using ping helps you quickly determine:

It’s one of the most basic yet powerful tools in any Linux user’s networking toolkit.


🛠️ Real-World Use Cases

ScenarioCommand
Check if you’re onlineping -c 4 google.com
Troubleshoot slow connectionsping google.com (observe response times)
Test local network devicesping 192.168.1.1
Monitor server availabilityping -c 10 server.example.com

📥 Exercise 3 – View or Download Data from a Server

In this exercise, you learned how to retrieve data from remote servers using two powerful command-line tools:

These tools are essential for:


🔍 Overview of What You Learned

TaskCommand
View file contents from a URLcurl [URL]
Download and save a filecurl -O [URL]
Download a file using wgetwget [URL]

✅ Step-by-Step Breakdown

🔹 3.1 Transfer Data from a Server Using curl

View file contents from a URL:

curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DB0250EN-SkillsNetwork/labs/Bash%20Scripting/usdoi.txt

This displays the full text of the U.S. Declaration of Independence directly in your terminal.

💡 This is useful when you want to inspect remote files without saving them.


Save the file to your current directory:

curl -O https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DB0250EN-SkillsNetwork/labs/Bash%20Scripting/usdoi.txt

Now you have a local copy named usdoi.txt.

📁 The -O option tells curl to save the file using its original filename.


🔹 3.2 Download Files Using wget

First, remove the file if it already exists:

rm usdoi.txt

Then download it again using wget:

wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DB0250EN-SkillsNetwork/labs/Bash%20Scripting/usdoi.txt

This downloads the file and saves it in your current directory.

⚙️ wget is especially useful because:

  • It works well in scripts
  • Supports recursive downloads (-r)
  • Can continue interrupted downloads (-c)
  • Doesn’t require user interaction once started

📋 Summary Table: curl vs wget

Featurecurlwget
View content in terminal✅ Yes❌ No
Save file with original name✅ With -O✅ Yes
Recursive download❌ No✅ Yes with -r
Resume broken download❌ By default✅ With -c
Works silently❌ Noisy by default✅ With -q
Use caseAPI calls, quick inspectionFile downloads, scripting

🧠 Why These Tools Matter

With curl and wget, you can:

They’re foundational tools for working with networked resources in Linux.


🛠️ Real-World Examples

🔽 Download a file silently with wget:

wget -q https://example.com/file.zip

🖥️ Download and display JSON from an API:

curl https://api.github.com/users/octocat

📂 Recursively download an entire website:

wget -r https://example.com

📥 Resume a partially downloaded file:

wget -c http://example.com/largefile.iso

Exercise 4 – Exploring DNS and Looking Up Domain Information

In this exercise, you’ll learn how to:

These tools are essential for:


🌐 What Is DNS?

DNS (Domain Name System) is like the phonebook of the internet.

It maps human-readable domain names (like google.com) to machine-readable IP addresses (like 172.217.174.78), so your computer knows where to find a website or service.

Key DNS Concepts:

TermMeaning
A RecordMaps a domain name to an IPv4 address
AAAA RecordMaps a domain to an IPv6 address
CNAMEAlias record pointing one domain to another
MX RecordSpecifies mail servers for a domain
NS RecordIdentifies authoritative name servers for a domain

🔍 Step-by-Step: Using nslookup

The nslookup command helps you query DNS servers to get domain-related information.

✅ View Basic DNS Info for a Website

nslookup google.com

This shows:


✅ Look Up Mail Servers (MX Records)

nslookup -type=mx gmail.com

This lists the mail exchange (MX) servers responsible for receiving emails for gmail.com.


✅ Query Name Servers (NS Records)

nslookup -type=ns ibm.com

This shows which name servers are responsible for managing the domain’s DNS records.


🔎 Step-by-Step: Using dig

dig (Domain Information Groper) is a more detailed and powerful tool than nslookup. It gives you full control over DNS queries.

✅ View A Record for a Domain

dig google.com

Look for the ANSWER SECTION:

google.com.     299     IN      A       172.217.174.78

This shows the IPv4 address that google.com resolves to.


✅ Look Up MX Records with dig

dig MX gmail.com

Scroll down to the ANSWER SECTION to see which servers handle email for Gmail.


✅ Get All DNS Records for a Domain

dig ANY ibm.com

This fetches all available DNS records for ibm.com, including:

⚠️ Some domains may restrict “ANY” queries for security reasons.


📋 Summary Table: Useful DNS Commands

TaskCommand
View basic DNS infonslookup google.com
Look up MX records (for email)nslookup -type=mx gmail.com
Look up name serversnslookup -type=ns ibm.com
View A recorddig google.com
View MX recordsdig MX gmail.com
View all DNS recordsdig ANY ibm.com

🧠 Why This Matters

Understanding DNS helps you:

Tools like nslookup and dig are invaluable for system administrators, developers, and anyone working with web services.


🛠️ Real-World Examples

ScenarioCommand
Check if a site resolves correctlydig example.com
Find who handles a domain’s emaildig MX example.com
Debug DNS propagation after changesdig @8.8.8.8 example.com (use Google’s public DNS)
Test local DNS cachenslookup example.com (before and after flush)

🛠️ Practice Exercises – Networking in Linux

These exercises will help reinforce your understanding of network-related commands in Linux. You’ll be working with tools like hostname, ping, ip, curl, and wget to inspect network configuration, test connectivity, and transfer data.


🔧 Before You Begin

Make sure you’re in the correct directory:

cd /home/project
pwd

You should see:

/home/project

Now let’s go through each exercise step-by-step.


✅ 1. Display Your Host’s IP Address

💡 Hint:

Use the hostname command with an option that shows the IP address.

✅ Solution:

hostname -i

This displays your system’s internal IPv4 address, such as:

172.17.0.2

This is useful for checking what IP address your machine is using on the local network.


✅ 2. Get Connectivity Stats on Your Connection to www.google.com

💡 Hint:

Use the ping command with a limited number of packets.

✅ Solution:

ping -c 5 www.google.com

This sends 5 ICMP echo requests to Google’s servers and returns stats like:

Example output:

--- www.google.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4005ms
rtt min/avg/max/mdev = 10.2/11.8/13.9/1.2 ms

This helps determine if your system can reach external sites and how fast it does so.


✅ 3. View Info About Your Ethernet Adapter eth0

💡 Hint:

Use the ip command to show details about the network interface.

✅ Solution:

ip addr show eth0

This shows:

Look for the line starting with inet — this is your IP address.

Example:

inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0

This is helpful when troubleshooting or configuring network interfaces.


✅ 4. View the HTML Code for www.google.com’s Landing Page

💡 Hint:

Use curl to fetch and display remote content.

✅ Solution:

curl www.google.com

This displays the raw HTML source code of Google’s homepage directly in your terminal.

Tip: If the output looks messy, try saving it to a file instead (next step).


✅ 5. Download the HTML Code for www.google.com’s Landing Page

💡 Hint:

Use wget to download and save the page.

✅ Solution:

wget www.google.com

This saves the downloaded HTML as:

index.html

Verify the file exists:

ls -l

You’ll see something like:

-rw-r--r-- 1 user user 12345 Apr 5 10:00 index.html

You now have a local copy of Google’s home page!


📋 Summary Table

TaskCommand
Show host IP addresshostname -i
Test connectivity to Googleping -c 5 www.google.com
View eth0 interface infoip addr show eth0
View HTML of Googlecurl www.google.com
Download Google’s HTMLwget www.google.com

File Archiving and Compression Commands in Linux


1. Introduction

✅ Understand the difference between archiving and compression
✅ Create and extract tarballs (.tar files)
✅ Compress and decompress using gzip and zip
✅ Extract contents from compressed archives

These skills are essential for:


2. Key Concepts

A. Archiving

B. Compression


3. Using tar – Tape ARchiver

Purpose

Create or extract archive files (called tarballs) that bundle directories and files.

Basic Syntax

tar [options] [archive_name.tar] [files_or_directories]

Common Options

OptionMeaning
-cCreate a new archive
-fSpecify filename
-tList contents of an archive
-xExtract files from archive
-zFilter through gzip (for compression/decompression)

A. Creating a Tar Archive

To archive a directory called notes:

tar -cf notes.tar notes/

Creates notes.tar, containing all files in the notes directory.


B. Listing Contents of a Tar File

To view what’s inside notes.tar:

tar -tf notes.tar

C. Extracting Files from a Tar Archive

To extract files:

tar -xf notes.tar

D. Compressing a Tar Archive with GZIP

To compress notes.tar into a smaller notes.tar.gz:

tar -czf notes.tar.gz notes/

This bundles and compresses the notes directory into a single compressed archive.


E. Extracting a .tar.gz File

To extract both the archive and its compressed contents:

tar -xzf notes.tar.gz

The -z option automatically handles gzip compression.


4. Using zip and unzip

A. What is zip?

Creating a ZIP Archive

To compress the notes folder into notes.zip:

zip -r notes.zip notes/

The -r flag ensures all subdirectories are included.


Listing Contents of a ZIP File

Use unzip to list contents:

unzip -l notes.zip

Extracting a ZIP File

To extract the contents:

unzip notes.zip

Automatically recreates the original directory structure.


5. Summary Table of Archiving & Compression Commands

TaskCommandDescription
Create tar archivetar -cf archive.tar folder/Bundle files into a single .tar file
List tar contentstar -tf archive.tarView files inside .tar
Extract tar archivetar -xf archive.tarUnpack .tar without compression
Create compressed tar.gztar -czf archive.tar.gz folder/Archive + gzip compression
Extract tar.gz filetar -xzf archive.tar.gzDecompress and unpack .tar.gz
Create zip archivezip -r archive.zip folder/Compress and bundle in .zip format
List zip contentsunzip -l archive.zipShow files inside .zip
Extract zip fileunzip archive.zipUncompress and unpack .zip

6. Comparison: tar vs zip

Featuretarzip
Primary UseArchiving (with optional compression)Archiving + built-in compression
Compression ToolUsually combined with gzip (tar.gz)Built-in compression
Cross-Platform SupportLimited on WindowsWidely supported
Recursive by DefaultYesRequires -r for folders
Preserves PermissionsYes (on Unix/Linux)No (on Windows)

7. Example Directory Structure

Suppose you have this directory:

notes/
├── math/
│   ├── week1.txt
│   └── week2.txt
└── physics/
    ├── week1.txt
    └── week2.txt

You can compress it into:

And later extract it back to the same structure using the appropriate command.


8. Final Tips


📦 Exercise 1 - File and Folder Archiving and Compression

In this exercise, you learned how to package, compress, and extract files using the Linux command line tools:

These are essential skills for:


🔧 Step-by-Step Breakdown

🔹 1.1 Create and Manage File Archives with tar

Create a .tar archive of the /bin directory:

tar -cvf bin.tar /bin

This creates a large file called bin.tar, which contains all files from the /bin directory.


List contents of the .tar archive:

tar -tvf bin.tar

This shows a detailed list of files inside the archive — useful for verifying contents before extraction.


Extract files from the .tar archive:

tar -xvf bin.tar

After extraction, you’ll see a folder named bin in your current directory.

Tip: Use ls -l to confirm it was extracted correctly.


🔹 1.2 Package and Compress Archive Files with zip

Create a .zip file of all .conf files in /etc:

zip config.zip /etc/*.conf

This bundles all configuration files ending in .conf into one compressed file: config.zip.


Create a compressed ZIP archive of an entire directory:

zip -ry bin.zip /bin

This compresses the entire /bin directory into a portable bin.zip file.


🔹 1.3 Extract, List, or Test ZIP Archives with unzip

List contents of a .zip file:

unzip -l config.zip

This shows what’s inside the archive without extracting anything — helpful for previewing.


Extract all files from a .zip archive:

unzip -o bin.zip

📋 Summary Table

TaskCommand
Create tar archivetar -cvf archive.tar directory/
List tar contentstar -tvf archive.tar
Extract tar archivetar -xvf archive.tar
Zip specific fileszip archive.zip file1 file2
Zip entire directoryzip -r archive.zip directory/
List zip contentsunzip -l archive.zip
Extract zip archiveunzip -o archive.zip

🧠 Why This Matters

Understanding archiving and compression helps you:

tar is commonly used in Linux environments for packaging, while zip offers cross-platform compatibility with Windows and macOS.


💡 Pro Tips


🎉 Module Summary & Highlights – Great Work!

You’ve successfully completed a comprehensive module that covers essential Linux command-line skills, from navigating the system and managing files to working with networks, processes, and archives.

Here’s a clean, organized summary of what you’ve learned — your Linux command cheat sheet for future reference.


🔧 Shell & Terminal Basics

TaskCommand
Start shellDefault shell is Bash
Display current userwhoami
Show user ID infoid
Get OS infouname -a
List directory contentsls, ls -l
Change directoriescd directory_name
Show current pathpwd
Find filesfind /path -name "filename"

📁 File and Directory Management

TaskCommand
Create filetouch filename
Make directorymkdir dirname
Copy file/dircp source destination
Move or renamemv old new
Remove filerm filename
Remove empty dirrmdir dirname
View file contentcat filename
View first N lineshead -N filename
View last N linestail -N filename
Count lines/words/charswc, wc -l filename
Sort linessort filename
Remove duplicatesuniq filename
Search in filesgrep "pattern" filename
Extract fieldscut -d "," -f2 filename
Merge files line-by-linepaste file1 file2

💾 Archiving and Compression

TaskCommand
Create .tar archivetar -cvf archive.tar folder/
List .tar contentstar -tvf archive.tar
Extract .tar archivetar -xvf archive.tar
Compress into .zipzip -r archive.zip folder/
List .zip contentsunzip -l archive.zip
Extract .zip archiveunzip archive.zip
Combine tar + gziptar -czvf archive.tar.gz folder/

🌐 Networking Tools

TaskCommand
View hostnamehostname
View IP addresshostname -i
Inspect network interfacesip addr or ip a
Test connectivityping www.google.com
Transfer datacurl https://example.com/file.txt
Download fileswget https://example.com/file.txt
Look up DNS recordsnslookup example.com or dig example.com

🖥️ System Monitoring & Info

TaskCommand
Disk spacedf -h
Running processesps -e, top
Current date/timedate
Print text/valuesecho "message"
Read manual pagesman command

🔒 File Permissions and Ownership

TaskCommand
View permissionsls -l
Change permissionschmod u+rwx filename
Change ownershipchown user:group filename (requires root)

🛠️ Text Processing & Data Wrangling

| Task | Command | | ------------------------ | ------------------------- | ----- | | Sort lines | sort filename | | Remove duplicate lines | sort file | uniq | | Extract patterns | grep "search" file | | Cut out columns | cut -d "," -f1 file.csv | | Merge files side-by-side | paste file1 file2 |


🧠 Why This Matters

You now have a solid foundation in:

These are core skills used daily by:


📄 Module 2 Cheat Sheet – Introduction to Linux Commands

This cheat sheet is your go-to reference for the most commonly used Linux commands in system navigation, file management, text processing, networking, and more.


Getting Information

TaskCommand
Show current userwhoami
Display user/group ID infoid
Show OS and kernel infouname -a
View command manualman top
List all available man pagesman -k .
Get help on a commandcurl --help
Show current date/timedate

🧭 Navigating and Working with Directories

TaskCommand
List files by date (newest first)ls -lrt
Find .sh files in directory treefind -name "*.sh"
Show current working directorypwd
Create a new directorymkdir new_folder
Move up one levelcd ../
Go to home directorycd ~ or just cd
Remove empty directoryrmdir temp_directory -v

🔍 Monitoring System Performance

TaskCommand
List running processesps
List all processesps -e
View real-time system statstop
Check disk space usagedf
Show disk usage of directoriesdu (not listed but useful)

📁 Creating, Copying, Moving, and Deleting Files

TaskCommand
Create an empty filetouch a_new_file.txt
Copy a filecp file.txt new_path/new_name.txt
Rename or move a filemv this_file.txt that_path/that_file.txt
Delete a filerm this_old_file.txt -v

🔐 Working with File Permissions

TaskCommand
Make file executable for everyonechmod +x my_script.sh
Give owner execute permissionchmod u+x my_file.txt
Remove read from group & otherschmod go-r filename
Change file ownershipchown user:group file (as root)

📖 Displaying File and String Contents

TaskCommand
View full file contentscat my_shell_script.sh
View file page-by-pagemore ReadMe.txt
View first N lineshead -10 data_table.csv
View last N linestail -10 data_table.csv
Print string or variableecho "I am $USERNAME"

🧹 Basic Text Wrangling

Sorting and Deduplication

TaskCommand
Sort file alphabeticallysort text_file.txt
Sort in reverse ordersort -r text_file.txt
Remove duplicate linesuniq list_with_duplicates.txt

Counting Lines/Words/Characters

TaskCommand
Count lines in a filewc -l table_of_data.csv
Count words in a filewc -w my_essay.txt
Count characters in a filewc -m some_document.txt

Searching with grep

TaskCommand
Search case-insensitively for “hello”grep -iw hello a_bunch_of_hellos.txt
List files containing “hello”grep -l hello *.txt

Merging Files with paste

TaskCommand
Merge files side-by-sidepaste first_name.txt last_name.txt phone_number.txt
Use comma as delimiterpaste -d "," first_name.txt last_name.txt phone_number.txt

Extracting Data with cut

TaskCommand
Extract first field (CSV)cut -d "," -f 1 names.csv
Extract bytes 2–5 from each linecut -b 2-5 my_text_file.txt
Extract from byte 10 onwardcut -b 10- my_text_file.txt

📦 Compression and Archiving

TaskCommand
Create tar archivetar -cvf my_archive.tar file1 file2
Compress with zipzip my_zipped_files.zip file1 file2
Compress directory with zipzip -r my_zipped_folders.zip dir1 dir2
Extract zip fileunzip my_zipped_file.zip
Extract zip to specific folderunzip my_zipped_file.zip -d extract_to_this_directory

🌐 Networking Commands

TaskCommand
Show hostnamehostname
Test network connectivityping www.google.com
Configure/view network interfacesip
Download content from URLcurl <url>
Download and save filewget <url>

🧠 Pro Tips


You’re now equipped with a powerful set of tools to work confidently in the Linux environment. Whether you’re managing servers, writing scripts, or analyzing logs — this cheat sheet will be your best companion.



Suggest Changes

Previous Post
Linux-M4 - Final Project