Operating System
An operating system, or OS, is like the manager of your computer. It's a special software that makes the hardware (like the physical parts of your computer) talk to the software (the programs and apps you use). Without an operating system, your computer and its software wouldn't know how to work together.
Key Roles of an Operating System:
-
Managing Programs: When you start your computer, the operating system is the first thing that gets loaded. It then makes sure all other programs (called applications) run smoothly.
-
Handling Memory: Decides how programs use the computer's memory.
-
Handling Devices: When you use things like printers or external hard drives, the operating system helps your computer communicate with these devices.
-
User Interaction: You can talk to the operating system, either by typing commands or using a graphical interface. It also tells you if something goes wrong or if a task is completed.
-
Task Management: If you're running multiple programs at the same time (multitasking), the operating system decides which ones get to run, in what order, and for how long.
and there are many other key roles such as Memory Management, Batch Jobs, and Parallel Processing.
How Users Interact:
You talk to the OS through commands or buttons on the screen (user interface). You tell it what you want, and it makes sure things happen.
Examples of Operating Systems:
- Redhat: Popular among Linux users.
- Microsoft Windows: Common on regular PCs.
- Apple MacOS: Exclusive to Apple computers.
- Ubuntu Linux: User-friendly variant of Linux for regular PCs.
- Google Android: Runs on many smartphones.
- iOS: Operating system for iPhones.
In simple terms, the operating system is like the boss that ensures everything in your computer runs smoothly and helps you communicate with it. Different computers use different operating systems.
Linux:
Linux is a open-source operating system kernel that serves as the core of various Unix-like operating systems. It was created by Linus Torvalds in 1991 and has since become a key component in the broader ecosystem of free and open-source software. In fact, one of the most popular platforms on the planet, Android, is powered by the Linux operating system.
Important Things to Remember in Linux
- Linux has a super-user account called root.
- Root is the most powerful account that can create, modify, delete accounts, and make changes to system configuration files.
- Linux is a case-sensitive system. ABC is NOT the same as abc.
- Avoid using spaces when creating files and directories.
- Linux kernel is not an operating system. It is a small software within Linux operating system that takes commands from users and passes them to system hardware or peripherals.
- Linux is mostly CLI (Command Line Interface) not GUI (Graphical User Interface).
- Linux is very flexible compared to other operating systems.
Access to Linux System
There are 2 types of access:
- Console: The console is direct access to an operating system when it is connected through VGA, HDMI, DVI, etc.
- Remote: The 2nd type of access is remote, where you connect to your operating system remotely over the network.
Remote Access Methods
RDP(Remote Desktop Protocol) Sharing
: Enables remote desktop access, commonly used in Windows environments.Putty
: A tool for connecting to remote systems using various protocols, such as SSH.SSH (Linux to Linux)
: Secure Shell protocol for secure remote access between Linux systems.
Download and Install Putty
- Putty is a software that allows you to connect from a Windows system to a Linux system remotely.
- If you are using Windows 10 or a newer version, you don't necessarily need to download or install PuTTY because Windows 10 includes a built-in SSH client. You can use the command:
ssh 192.168.1.5
.
Access to Linux from MAC
- Open a terminal on your MAC.
- Run the following command:
ssh –l iafzal 192.168.1.5
.
Understanding the Linux Filesystem:
Think of a filesystem as the way your computer organizes and keeps track of files on its storage, like a digital filing cabinet. It's like the method your computer uses to know where each file is stored on your hard drive or other storage devices.Operating system stores files and directories in an organized and structured way
.
Key Components:
1. Superblock: Think of it as the table of contents for the entire filing system. It contains crucial information about the overall filesystem, like its size.
2. Inode: This is like a file's ID card. It holds all the details about a file, except its name.
3. Data Block: Imagine this as the actual storage unit where the content of a file is kept.
4. Directory Block: This is like a folder that contains filenames and their corresponding Inode numbers.
5. Indirection Block: Think of it as a map guiding your computer on where to find data blocks efficiently.
Making Sense of Filesystem Structure
When you store a file on your computer, the filesystem organizes it in a structured way:
- The Superblock oversees everything.
- Inodes store details about each file.
- Directory Blocks keep track of filenames and their corresponding Inode numbers.
- Data Blocks store the actual content of the files.
Filesystem Hierarchy Standard (FHS)
1. Root Filesystem (/):
- Core of the computer's brain.
- Essential files for booting up and fixing problems.
- Specific to each machine and can be on a network drive.
2. /usr Filesystem:
- Library-like space.
- Holds commands, libraries, and manuals for regular use.
- Files are shared over the network for space-saving and easy updates.
3. /var Filesystem:
- Dynamic storage for changing files (logs, temporary files).
- Used to be part of /usr but separated for flexibility.
4. /home Filesystem:
- Personal space for user home directories.
- Separated for easy backups; can be split further, e.g., /home/students and /home/staff.
Why It Matters
- Organizes files by purpose (commands, data, docs).
- Prevents messy structures like grouping by program.
- Keeps the root filesystem small for safety; a corrupted root can make the system unbootable.
In simple terms, it's like having specialized areas in your computer for different tasks—booting up, regular operations, dynamic changes, and personal stuff. Everything has its place to keep things tidy and working smoothly.
Linux Filesystem Hierarchy
The Linux Filesystem follows a hierarchical structure, represented as a tree with the root directory ("/") at its pinnacle. Let's explore the primary directories within this hierarchy:
1. / (Root Directory)
The root directory is the starting point of the Linux filesystem. All other directories and files stem from the root. It is denoted by a single forward slash ("/").
2. /bin - User Binaries: (/usr/bin
)
The /bin
directory contains essential binary executables that are crucial for the basic functioning of the system. These binaries are fundamental to system recovery, particularly in scenarios where the /usr
directory is inaccessible.
- Common commands used by all users (e.g., ps, ls, ping).
3. /sbin - System Binaries: (/usr/sbin
)
Similar to /bin
, the /sbin
directory contains binary executables, but these are specifically for system administration tasks. These binaries are essential for system maintenance and recovery (e.g., iptables, reboot, fdisk).
4. /etc (Etcetera):
- Contains configuration(settings and preferences) files for different programs.
- Includes startup and shutdown scripts.
- Examples: /etc/resolv.conf, /etc/logrotate.conf.
5. /home - Home Directories:
- User home directories are situated in
/home
. Each user typically has a dedicated subdirectory here for personal files and configurations. For example: /home/samyak
6. /tmp - Temporary Files:
The /tmp
directory is a location for storing temporary files. It is accessible by all users and is typically used for temporary data that does not need to persist across reboots, so gets cleared.
7. /boot - Boot Loader Files:
- Contains boot loader-related files(files needed when the computer starts up).
- Includes kernel, initrd, grub files.
8. /lib and /lib64 - System Libraries: (/usr/lib
)
The /lib
and /lib64
directories contain dynamic link libraries (shared libraries) that are essential for the execution of binaries in /bin
and /sbin
.
- Files named ld* or lib*.so.*.
- eg. C programming library files needed by commands and apps
9. /proc(Process Information) and /sys(System Information):
The /proc
and /sys
directories provide interfaces to kernel and system information. They allow users to interact with and retrieve details about running processes, kernel parameters, and system configurations.
- Pseudo filesystem with data about running processes.
- Virtual filesystem with text info about system resources (e.g., /proc/uptime).
10. /media and /mnt (Mount Points):
These directories are used for temporarily mounting external storage devices. The /media
directory is often used for automatically mounted devices, while /mnt
is a generic mount point for manually mounted devices.
- Media holds Temporary mount directory for removable devices (e.g., CD-ROM, floppy drives). -/media is supposed to be the mount point for removable media while /mnt is for temporary mounts initiated by the user.
11. /root:
The /root
directory is the home directory for the root user, the superuser who has administrative privileges. Unlike regular user home directories in /home
, the root user's home is located directly under /
.
12. /srv - Service Data:
The /srv
directory is designed to contain data directories for services provided by the system. This can include data related to websites, FTP servers, or other services.
- Has data related to specific services or tasks your computer performs.
- Contains server-specific service-related data (e.g., /srv/cvs for CVS).
13. /opt (Optional):
The /opt
directory is reserved for the installation of optional software packages. It provides a convenient location for storing applications that are not part of the default system installation.
14. /dev (Device):
In Linux, everything is treated as a file, including devices. The /dev
directory contains device files that serve as interfaces to various hardware devices connected to the system (e.g., disk, cdrom, speakers, flash drive, keyboard, etc).
/run
: System daemons that start very early (e.g., systemd and udev) to store temporary runtime files like PID files.
15. /usr (User):
The /usr
directory contains user-related system files and program binaries. It is often the largest directory on a Linux system and is organized into subdirectories like /usr/bin
, /usr/lib
, and /usr/share
.
- /usr/bin
This subdirectory holds non-essential command binaries for all users.
- /usr/include
Header files for C and C++ programming languages are stored here.
- /usr/lib
Libraries for programs in /usr/bin
are stored in this directory.
- /usr/local
The /usr/local
directory is typically used for locally installed software and binaries.
16. /var (Variable):
The /var
directory contains variable data, such as logs, spool files, and temporary files generated by various system processes. It is crucial for dynamic data that changes during the system's runtime.
- /var/log
Log files from various programs and services are stored in this subdirectory.
- /var/spool
Spool directories for services like mail and print are located here.
- /var/tmp
Similar to /tmp
, this directory is used for temporary files but with a longer persistence.
Mounting Filesystems
Mounting is the process of attaching a filesystem to a directory in the Linux Filesystem Hierarchy. The mount
command is used for this purpose. >For example:
sudo mount /dev/sdb1 /mnt/data
This command mounts the filesystem on /dev/sdb1
to the /mnt/data directory
.
- /etc/fstab The
/etc/fstab
file contains information about filesystems and their properties, including mount points. This file is read at boot time to >automatically mount specified filesystems.
Filesystem Types in Linux:
Linux supports various filesystem types, each with its own characteristics. Here are some commonly used filesystems:
- ext4 (Fourth Extended Filesystem)
The default filesystem for many Linux distributions, ext4 is known for its reliability, scalability, and backward compatibility with its predecessors (ext2 and ext3).
- XFS
XFS is designed for scalability and high-performance. It is commonly used in enterprise environments and supports large file systems and files.
- Btrfs (B-Tree File System)
Btrfs is a modern filesystem with features such as snapshots, compression, and checksums. It is designed to improve fault tolerance and facilitate easy system administration.
- ZFS (Zettabyte File System)
ZFS is known for its advanced features, including data integrity, snapshots, and copy-on-write. While not the default in most Linux distributions, it is used in some environments for its robust capabilities.
File Permissions and Ownership
Linux employs a robust permission system to control access to files and directories. Permissions are categorized into read (r), write (w), and execute (x) for the owner, group, and others. The chmod
command is used to modify permissions.
Ownership
Ownership of files and directories is determined by a user and a group. The chown
and chgrp
commands allow changing the ownership of files.
sudo chown user:group filename
: This command changes the owner and group of the specified file. eg:
sudo chown john:marketing document.txt
- Only the root user (or a user with sudo privileges) can change file ownership.
- The specified user and group must exist on the system.
- You can change ownership for multiple files using wildcards (e.g., sudo chown john:marketing *.txt to change ownership of all .txt files).
- To change only the owner, omit the group part (e.g., sudo chown john filename).
- To change only the group, use the chgrp command (e.g., sudo chgrp marketing filename).
Special Permissions
Linux also supports special permissions, including the set user ID (SUID), set group ID (SGID), and sticky bit. These special permissions provide additional control over how executables are run and how directories are accessed.
Navigating File System
-
Important commands for navigating a UNIX filesystem:
cd
: Change directory : cd /path/to/directorypwd
: Print working directory : prints the current working directory's full path.ls
: List all directories/files within a current working directory. Common options include: -l: Detailed (long) listing (ls -l). -a: Show hidden files (ls -a). -h: Human-readable file sizes (ls -h).
-
Using the TAB key for auto-completion.
cp
: used to copy files or directories.mv
: used to move or rename files and directories.rm
: used to remove files or directories.mkdir
: used to used to create directories.rm
: used to remove files or directories.rm
: used to remove files or directories.
Linux File or Directory Properties
In Linux, every file or directory has properties that describe it. These properties include:
- Type: Specifies whether it's a file or directory.
- Number of Links: Indicates how many hard links point to the file.
- Owner: The user who owns the file or directory.
- Group: The group associated with the file or directory.
- Size: The size of the file in bytes.
- Month, Day, Time: The last modification date and time.
- Name: The name of the file or directory.
Linux File Types
In Linux, when you use commands like ls
to list files, different characters in the output represent various file types:
- Regular File: Displayed as a hyphen (-).
- Directory: Displayed as a letter "d".
- Symbolic Link (Symlink): Displayed as an "l" followed by the linked file's path.
- Character Device: Displayed as a letter "c" followed by device information.
- Block Device: Displayed as a letter "b" followed by device information.
- Named Pipe (FIFO): Displayed as a letter "p".
- Socket: Displayed as a letter "s".
- Door (Solaris): Displayed as a letter "D".
Root in Linux
There are three contexts in which "root" is used in Linux:
1. Root Account: The superuser account with the highest privileges. It can access all commands and files.
2. Root Directory (/): The base directory of the Linux file system. All other directories and files are contained within it.
3. Root Home Directory (/root): The home directory of the root user. It's located within the root directory.
Managing Files and Directories in Linux:
Changing Password
- Change your initial password as soon as you log in.
- To change your password in Linux, use the
passwd
command:
passwd userid
- Old password: Enter your current password.
- New password: Enter your new password.
- Retype new password: Retype your new password for confirmation.
File System Paths
- Two paths to navigate to a filesystem:
- Absolute Path
- Relative Path
- Absolute path always begins with a "/", indicating that the path starts at the root directory. It provides a complete, unambiguous route. Absolute paths are universal: They work regardless of your current location, ensuring consistency. Example: /home/user/documents/report.txt leads directly to the file "report.txt" from the root directory.
- Relative path does not begin with a "/". It identifies a location relative to your current position. Relative paths offer flexibility: They can be shorter and adapt to different starting points. Example: If you're in /home/user, the relative path documents/report.txt also leads to "report.txt".
Some Useful Commands
Creating Files
-
touch
Command: Quickly creates empty files.Example:
touch filename.txt
creates an empty file named "notes.txt". -
cp
Command: Copies existing files, creating new ones in the process.Example:
cp report.docx backup_report.docx
creates a copy of "report.docx" named "backup_report.docx". -
vi
Command: Opens the Vi text editor to create or edit files.Example:
vi newfile.txt
opens "presentation.txt" for editing (if it doesn't exist, it creates it).
Creating Directories
-
mkdir
Command: Creates new directories (folders).Example:
mkdir project_files
creates a directory named "project_files".
Copying Directories
-
cp -R
Command: Copies directories and their contents recursively.Example:
cp -R photos/ vacation_backup
copies the entire "photos" directory and its contents to a new directory named "vacation_backup".
Find Files and Directories
-
find
Command- Usage:
find / -name filename.txt
(Syntax:find [path] [options] [expression]
) - Description: Searches the entire filesystem for a file named
filename.txt
. - Note: Offers extensive options for refined searches which can take time. find [path] [options] [expression]
- Usage:
-
locate
Command- Usage:
locate filename.txt
(Syntax:locate [filename]
) - Description: Provides a quicker alternative to
find
by using a pre-built database. - Trade-off: May not show the latest results, as the database is not updated in real-time. The system runs
updatedb
once a day to create a snapshot of the file system, whichlocate
uses for quick reporting. But recent additions or removals within the last 24 hours are not reflected in the snapshot.
- Usage:
-
updatedb
Command: Updates thelocate
command's database, ensuring it reflects the current state of the filesystem.
find
is highly configurable with numerous options to tailor the search efficiently. On the contrary,locate
relies on a pre-built database. >If the database isn't updated, thelocate
command won't show the latest results. To sync the database, use theupdatedb
command. This command ensures thelocate
database is current.find
supports various search criteria like name, size, modification time, permissions, and more.
Wildcards
Wildcards act as placeholders in searches, helping you find files or patterns even when you don't know the exact names or text. Basically characters used as substitutes for any class of characters in a search.
*
(Asterisk): Represents any number of characters (including zero).
- Eg:
file*.txt
matchesfile1.txt
,file2.txt
, etc.
report*
matchesreport.doc
,reports.xlsx
,report_final.pdf
, and evenreport
.
?
(Question Mark): Represents a single character, any character.
- Eg:
file?.txt
matchesfile1.txt
,fileA.txt
, but notfile.txt
orfile123.txt
.
[]
(Square Brackets): Represents a range of characters in a search.
- Eg:
file[1-3].txt
matchesfile1.txt
,file2.txt
, andfile3.txt
.
data[abc].csv
matchesdataa.csv
,datab.csv
, anddatac.csv
.
Soft and Hard Links
Soft links and hard links are two types of links in Linux that point to files. Let's break down the example you provided to understand the differences:
Create two files:
$ touch blah1
$ touch blah2
Enter some data into them:
$ echo "Cat" > blah1
$ echo "Dog" > blah2
Adds the text "Cat" to blah1
and "Dog" to blah2
.
And as expected:
$ cat blah1; cat blah2
Cat
Dog
Let's create hard and soft links:
$ ln blah1 blah1-hard
$ ln -s blah2 blah2-soft
blah1-hard
is a hard link to blah1
.
blah2-soft
is a soft link (symbolic link) to blah2
Let's see what just happened:
$ ls -l # list files, The -l option with ls provides detailed information. You can see the links.
blah1
blah1-hard
blah2
blah2-soft -> blah2
Changing the name of blah1 does not matter:
$ mv blah1 blah1-new
Renaming blah1
to blah1-new
does not affect blah1-hard
.
$ cat blah1-hard
Cat
The hard link still points to the same inode and retains the original content.
$ mv blah2 blah2-new
Renaming blah2
to blah2-new
affects the soft link.
$ ls blah2-soft
blah2-soft
The soft link still exists, but it's pointing to a non-existing file.
Delete Files
If blah1
is deleted, blah1-hard
still holds the content.
If blah2
is deleted, blah2-soft
is just a link to a non-existing file, and its content cannot be found.
In Summary
Hard Links:
- Directly points to the inode (data blocks) of the file.
- Renaming or moving the original file does not affect hard links.
- Retains content even if the original file is deleted until all hard links are deleted.
Soft Links (Symbolic Links):
- Points to the filename or path of the original file.
- Affected by renaming or moving the original file.
- Becomes invalid if the original file is deleted.
Command Prompts and Getting Prompts Back
-
Command Prompts: A short text at the start of the command line followed by a prompt symbol on a command line interface.
- Example:
username@hostname Prompt symbol
- Example:
-
To get your prompt back:
- Press
Ctrl + c
.
- Press
Linux Fundamentals
Command Syntax
In Linux, commands generally follow this structure: command option(s) argument(s)
.
-
Options: Modify command behavior, often a single letter after a hyphen. Multiple options can be grouped together.
-
Arguments: Used with commands, can be optional or required. Some commands have default arguments if none are provided.
ls -l -a /path/to/directory
or
ls -la /path/to/directory # `-la` is a shorthand for combining both `-l` and `-a` options.
Here, ls
is the command, -l
and -a
are options modifying its behavior, and /path/to/directory
is the argument specifying the directory whose contents you want to list.
- Options:
-l
(long format) and-a
(show hidden files)
File Permissions
-
UNIX is a multi-user system.
-
Every file and directory can be protected or made accessible to other users by changing access permissions.
-
Three types of permissions:
r
- readw
- writex
- execute (for running a program)
-
Each permission (
rwx
) can be controlled at three levels:u
- user (yourself)g
- group (people in the same project)o
- other (everyone on the system)
-
You can Display permissions with ls -l (e.g., -rwxrwxrwx).
-
Command to change permissions:
chmod
Permission Using Numeric Mode
In Linux, you can assign permissions to files and directories using numeric values. This method provides a concise way to represent the various permission settings. Examples:
- Using the
chmod
command:chmod ugo+r FILE
orchmod 444 FILE
(makes the file read-only for everyone).
File Ownership
In Linux, Every file or directory in Linux has two owners: a user and a group.
Changing Ownership:
-
chown
: Used to change the user owner of a file or directory.Example:
chown newuser myfile.txt
-
chgrp
: Used to change the group owner of a file or directory. Example:chgrp newgroup myfile.txt
Recursive Ownership Change:
When you need to change ownership not just for a file or directory but also for all its contents, use the -R
option with chown
or chgrp
.
Helpful Commands and Techniques:
Help Commands
1. whatis command: Provides a brief description of a command.
Example: whatis ls
2. command --help: Displays a summary of a command's usage and options.
Example: ls --help
3. man command: Opens the manual pages for a command, providing in-depth documentation.
Example: man ls
TAB Completion and Up Arrow
TAB Completion:
- Pressing the TAB key auto-completes commands, file names, or directories, reducing typing effort.
Up Arrow Key:
- Pressing the up arrow recalls the last executed command, allowing for quick reuse.
Adding Text to Files (Redirects)
-
Using
vi
: Open the text editor to manually add or edit text.Example:
vi myfile.txt
-
Redirecting Command Output:
>
overwrites the file:echo "Hello" > greeting.txt
(will overwrite "Hello" to greeting.txt.)>>
appends to the file:echo "World" >> greeting.txt
(will append "World" to the existing content in greeting.txt.) -
Using
echo
: Example:echo "Hello Linux" > greeting.txt
echo
is a simple command to print text. When used with >, it writes the specified text to the specified file, overwriting its content.
Input and Output Redirects
Standard Input/Output/Error:
stdin
(0),stdout
(1), andstderr
(2) are file descriptors. Think of these as channels for input, output, and error messages when running commands.
Examples of Redirecting Output:
- Redirect
ls
output to a file:ls -l > listings
This saves the output of thels -l
command to a file calledlistings
, replacing its content if it exists. - Append
ls
output to a file:ls -la >> listings
This appends the output ofls -la
to the filelistings
, preserving its existing content. - Redirect text to a file:
echo "Hello World" >> findpath
This appends the text "Hello World" to a file namedfindpath
Standard Output to a File (tee
Command)
- Used to store and view the output of a command simultaneously.
- Example:
ls -l | tee output.txt
This command lists the files (ls -l
) and simultaneously stores the output in a file namedoutput.txt
.
Pipes
- Connects the output of one command to the input of another using the
|
symbol. - Example:
ls -l | more
This command lists the files in long format (ls -l
) and pipes the output to themore
command, allowing you to scroll through the output page by page.
File Maintenance Commands
cp
(copy)rm
(remove/delete)mv
(move/rename)mkdir
(create directory)rmdir
orrm -r
(remove directory)
chgrp (change group):
- This command is used to change the group ownership of files or directories in Linux.
- Example:
chgrp newgroup myfile.txt
- It assigns the file
myfile.txt
to a new group callednewgroup
.
chown (change owner):
chown
changes the user owner of a file or directory.- Example:
chown newuser myfile.txt
- It assigns the file
myfile.txt
to a new user callednewuser
.
File Display Commands
cat
(concatenate and display) The cat command is used to display the contents of a file or concatenate multiple files together. Example: cat myfile.txtmore
(display page by page) Example: more myfile.txt It shows the file's content page by page, allowing you to navigate using spacebar or Enter.less
(display with navigation) Similar to more, but less provides more navigation options. Example: less myfile.txt It allows scrolling up and down, searching, and other navigation features for file content.head
(display the beginning) Example: head myfile.txt It shows the first few lines (by default, the first 10 lines) of myfile.txt.tail
(display the end) Example: tail myfile.txt It shows the last few lines (by default, the last 10 lines) of myfile.txt.
Filters / Text Processors Commands
These commands process and manipulate text:
cut (select portions):
cut
extracts specific portions or columns from a file.- Example:
cut -d',' -f1,3 file.csv
- It selects and displays specific columns (1st and 3rd in this example) from
file.csv
delimited by a comma.
awk (text processing):
awk
is a powerful text-processing tool for pattern scanning and processing.- Example:
awk '/pattern/' file.txt
- It searches for and processes lines in
file.txt
containing the specified pattern.
grep and egrep (pattern matching):
grep
andegrep
search files for specific patterns.- Example:
grep "search_text" myfile.txt
- It displays lines in
myfile.txt
that contain the specified "search_text".
sort (sort lines):
sort
arranges the lines in a file in alphabetical or numerical order.- Example:
sort myfile.txt
- It displays the content of
myfile.txt
sorted alphabetically by default.
uniq (display unique lines):
uniq
filters out adjacent duplicate lines from a file.- Example:
uniq myfile.txt
- It displays only unique lines from
myfile.txt
.
wc (word count):
wc
counts lines, words, and characters in a file.- Example:
wc -l myfile.txt
- It counts the number of lines in
myfile.txt
.
Compare Files
When you need to check the differences between two files in Linux, you have a couple of options:
diff
: Compares files line by line.
- Example:
diff file1.txt file2.txt
It will display the lines that differ between the two files.
cmp
: Compares files byte by byte.
- Example:
cmp file1.txt file2.txt
It's useful for binary files or when you want a byte-level comparison.
Compress and un-Compress Files
File compression is handy for saving space and bundling files together:
tar
: Stands for "tape archive." It's used to create archives that can contain multiple files and directories.
Example: tar -cvf archive.tar file1.txt dir1
-c
: Creates a new archive.-v
: Verbosely shows the progress of the operation.-f
: Specifies the filename of the archive.archive.tar
: name of the archive file that will be created.file1.txt dir1
: These are the files and directories that will be included in the archive.
gzip
or gunzip
: gzip
compresses files, and gunzip
decompresses them.
Example: gzip file.txt (compress) / gunzip file.txt.gz (decompress)
gzip
: Stands for "GNU zip." It's used to compress files.gunzip
: Counterpart ofgzip
, used to decompress compressed files.file.txt
: Name of the file that you want to compress or decompress.file.txt.gz
: This is the compressed version offile.txt
created bygzip
. The original file is typically replaced by the compressed version.gunzip file.txt.gz
: The compressed file is usually deleted after decompression.
Truncate File Size (truncate
)
Useful for quickly resizing files without altering their content.
truncate –s 10 filename
: Reduces or extends the size of a file to a specified length(in this case 10 bytes).
Combining and Splitting Files
Manipulating files by combining or splitting them is a common task:
- Combining using
cat
:cat file1 file2 file3 > file4
concatenates the contents of files 1, 2, and 3 into a new file, file4. - Splitting using
split
:split -l 300 file.txt childfile
splits file.txt into smaller files, each containing 300 lines. Useful for breaking down large files into more manageable pieces.
Linux vs. Windows Commands
Command Description | Windows | Linux |
---|---|---|
Listing of a directory | dir | ls -l |
Rename a file | ren | mv |
Copy a file | copy | cp |
Move file | move | mv |
Clear screen | cls | clear |
Delete file | del | rm |
Compare contents of files | fc | diff |
Search for a word/string in a file | find | grep |
Display command help | command /? | man command |
Displays your location in the file system | chdir | pwd |
Displays the time | time | date |