An open API service indexing awesome lists of open source software.

https://github.com/rnaveensrinivas/linux

Notes for learning Linux. This repository contains key concepts, commands, tutorials, and practical tips for using and managing Linux systems.
https://github.com/rnaveensrinivas/linux

bash bash-script linux linux-shell ubuntu ubuntu2404lts

Last synced: about 1 month ago
JSON representation

Notes for learning Linux. This repository contains key concepts, commands, tutorials, and practical tips for using and managing Linux systems.

Awesome Lists containing this project

README

          

# Table of Contents
* [Introduction](#Introduction)
* [Linux Directory Structure](#Linux-Directory-Structure)
* [Summary](#Summary-of-Linux-Directory-Structure)
* [Command Line Interface](#Command-Line-Interface)
* [Basic Commands](#Basic-Commands)
* [Summary](#Summary-of-Basic-Commands)
* [Directories](#Directories)
* [Summary](#Summary-of-Directory-Commands)
* [Viewing File and Directory Details](#Viewing-File-and-Directory-Details)
* [Summary](#summary-of-viewing-file-and-directory-commands)
* [Permissions](#Permissions)
* [Summary](#summary-of-permissions-commands)
* [Viewing and Editing Files](#Viewing-and-Editing-Files)
* [Summary](#summary-of-viewing-files)
* [The Vim Editor](#the-vim-editor)
* [Summary](#Summary-of-Vim-Commands)
* [The Vim Editor](#the-vim-editor)
* [Summary](#summary-of-vim-commands)
* [Deleting, Moving, and Renaming Files and Directories](#deleting-moving-and-renaming-files-and-directories)
* [Summary](#Summary-of-Deleting-Moving-and-Renaming-Files-and-Directories-Commands)
* [Finding, Sorting, and Comparing Files and Directories](#finding-sorting-and-comparing-files-and-directories)
* [Summary](#Summary-of-Finding-Sorting-and-Comparing-Files-and-Directories)
* [I/O Redirection](#io-redirection)
* [Summary](#Summary-of-IO-Redirection-Commands)
* [Additional Command Line Concepts](#Additional-Command-Line-Concepts)
* [Summary](#Summary-of-Additional-Command-Line-Concept-Commands)
* [Processes and Jobs](#Processes-and-Jobs)
* [Summary](#Summary-of-Processes-and-Jobs-Control-Commands)
* [Switching Users](#Switching-Users)
* [Summary](#Summary-of-Switching-User-Commands)
* [Installing Software](#Installing-Software)
* [Summary](#Summary-of-Installing-Software-Commands)
* [**CheatSheet**](#Cheat-Sheet)
---

# Introduction

## What is Linux?
Linux is a **Unix-like open-source operating system** renowned for its flexibility, security, and extensive community support. At its core is the **[Linux kernel](https://github.com/torvalds/linux)**, the foundational component that bridges the gap between applications and hardware. The kernel manages system resources, ensures hardware-software communication, and provides essential services like memory management and process control.

### Key Characteristics of Linux
- **Unix-like**: Shares architectural and conceptual similarities with Unix.
- **Open Source**: Freely available for use, modification, and distribution.
- **Kernel-Centric**: The kernel serves as the foundation of the operating system.

---

## A Brief History of Linux
Linux was created in **1991** by **Linus Torvalds**, a Finnish computer science student, as a personal project to develop a free and open-source alternative to proprietary Unix systems. Inspired by **Minix**, a Unix-like system for educational purposes, Torvalds initially released the kernel under a proprietary license but soon adopted the **GNU General Public License (GPL)**. This move aligned Linux with the **GNU Project**, initiated by **Richard Stallman**, which aimed to create a completely free operating system.

Since its inception, Linux has evolved through collaboration between Torvalds and a global community of developers. Today, it powers desktops, servers, embedded systems, and supercomputers, becoming one of the most versatile and widely used operating systems.

---

## Linux Distributions
A **Linux distribution (distro)** is a complete operating system built around the Linux kernel. Distributions bundle essential software, tools, and utilities tailored to various purposes, creating a cohesive and usable environment.

### Features of Linux Distributions
1. **Shared Core**: All distributions are built on the Linux kernel.
2. **Custom Software**: Each distribution bundles software, tools, and configurations based on its focus.
3. **Targeted Use Cases**: Some distributions cater to **desktops** (e.g., Linux Mint), others to **servers** (e.g., CentOS, RHEL), while some serve both (e.g., Ubuntu).
4. **Support Models**: Distributions are maintained by either **community** volunteers or **corporations** offering professional support.

### Popular Linux Distributions

| **Distribution**| **Primary Usage** | **Support Model**| **Notes** |
|--------------------------|-------------------|-----------------------|---------------------------------------------------------------------------|
| **Linux Mint** | Desktop | Community | User-friendly, ideal for beginners. |
| **Ubuntu** | Both | Community | Widely used with LTS versions for stability. |
| **Debian** | Both | Community | Stable and reliable, popular for servers. |
| **Fedora** | Both | Community | Cutting-edge features, upstream for RHEL. |
| **openSUSE** | Both | Community/Corporate | Offers Leap (stable) and Tumbleweed (rolling release) versions. |
| **Arch Linux** | Desktop | Community | Minimalist and highly customizable. |
| **CentOS** | Server| Community | RHEL-based, stable, enterprise-ready. |
| **RHEL** | Server| Corporate | Commercial support for enterprise environments. |
| **Manjaro** | Desktop | Community | Arch-based with user-friendly tools. |
| **Elementary OS**| Desktop | Community | Aesthetic design, excellent for newcomers.|
| **Kali Linux** | Desktop | Community | Specialized for penetration testing and security tasks. |
| **Zorin OS** | Desktop | Community | Perfect for users transitioning from Windows. |
| **Pop!_OS** | Desktop | Community | Developer- and gamer-friendly, based on Ubuntu. |
| **AlmaLinux**| Server| Community | RHEL clone, focused on enterprise users. |
| **Slackware**| Both | Community | Traditional UNIX-like experience. |
| **MX Linux** | Desktop | Community | Lightweight and efficient for older hardware. |

**Legend**:
- **Desktop**: Tailored for personal or workstation use.
- **Server**: Designed for stability, often used in enterprise or hosting environments.
- **Community**: Developed and maintained by volunteers.
- **Corporate**: Backed by companies providing commercial support.

---

## Why Learn Linux?
The core principles and functionalities of Linux remain consistent across distributions, making it a universal skill for tech enthusiasts and professionals. Linux powers:
- **90% of the world's supercomputers**,
- **96.3% of the top 1 million web servers**,
- **74% of smartphones (via Android)**.

Its unmatched flexibility, security, and open-source nature have made Linux a cornerstone of modern technology. Learning Linux opens doors to diverse career opportunities and empowers you to work efficiently in today's computing environments.

---

# Linux Directory Structure

The Linux directory structure is hierarchical, resembling an inverted tree with the **root** or **trunk** (`/`) as its base. All directories branch off from the root, with forward slashes (`/`) separating directories.

**Directory** is nothing but a linux jargon for **folder**.

## Common Top-Level Directories

### `/` Root Directory
The root of the Linux file system, often referred to as the **slash (/)** or the **trunk**, serves as the starting point for all files and directories. Everything in Linux resides under `/`. This is similar to `C:\` in Windows. However, unlike Windows, where additional storage is assigned drive letters like `D:\`, Linux mounts additional storage devices as subdirectories, typically under locations like `/mnt` or `/media`.

```bash
$ ls /
bin dev lib64 mnt run srv usr
bin.usr-is-merged etc lib.usr-is-merged opt sbin swap.img var
boot home lost+found proc sbin.usr-is-merged sys
cdrom lib media root snap tmp
```

### `/bin` Binaries
Contains **essential executable programs** (e.g., basic commands like `ls`, `cp`). Additional non-essential binaries like graphical apps, mail, and trivial cmd utitlies are found in `/usr/bin`.
```bash
$ ls /bin
'[' mpris-proxy
aa-enabled mpstat
aa-exec mscompress
aa-features-abi msexpand
aconnect mt
acpidbg mt-gnu
add-apt-repository mtr
addpart mtrace
addr2line mtr-
...
```

### `/etc` System Configuration Files
Houses **configuration files** that controls how the operating system and applications (e.g., boot modes, nareetwork settings) behave.
```bash
$ ls /etc
adduser.conf fuse.conf logrotate.d rsyslog.d
alsa fwupd lsb-release rygel.conf
alternatives gai.conf machine-id sane.d
anacrontab gdb magic security
apache2 gdm3 magic.mime selinux
apg.conf geoclue manpath.config sensors3.conf
apm ghostscript mime.types sensors.d
apparmor glvnd mke2fs.conf services
apparmor.d gnome ModemManager sgml
apport gnome-remote-desktop modprobe.d shadow
apt gnutls modules shadow-
avahi gprofng.rc modules-load.d shells
bash.bashrc groff mtab skel
bash_completion group nanorc snmp
bash_completion.d group- netconfig speech-dispatcher
bindresvport.blacklist grub.d netplan ssh
binfmt.d gshadow network ssl
...
```

### `/home` Home Directories
Each user on a Linux system has a subdirectory dedicated to their account in the /home directory. For example,Example: `/home/sri`.
```bash
$ ls /home/
sri
```

### `/opt` Optional or Third-Party Software
Used for **software not bundled with the operating system**, like Google Chrome.

**Fact** - Firefox comes builtin with the operating system.
```bash
$ whereis firefox
firefox: /usr/bin/firefox /snap/bin/firefox
```

### `/tmp` Temporary Files
Temporary workspace for applications and users. Files here are **cleared at boot time**.
```bash
$ ls /tmp
snap-private-tmp
systemd-private-9e8bed51413f4d929422b8d7d854bbcd-bluetooth.service-rcvxLj
systemd-private-9e8bed51413f4d929422b8d7d854bbcd-colord.service-1fPQpU
systemd-private-9e8bed51413f4d929422b8d7d854bbcd-fwupd.service-RclrPC
systemd-private-9e8bed51413f4d929422b8d7d854bbcd-ModemManager.service-ItsVvS
...
```

### `/usr` - User-Related Data
The `/usr` directory contains user-related programs and **read-only data**, which are not essential for the operating system's core functionality. Subdirectories include:
- `/usr/bin`: Executable programs.
- `/usr/lib`: Libraries.
- `/usr/share/doc`: Shared documentation and resources.

#### `/usr`
```bash
$ ls /usr
bin games include lib lib64 libexec local sbin share src
```
#### `/usr/bin`
```bash
$ ls /usr/bin
'[' mpris-proxy
aa-enabled mpstat
aa-exec mscompress
aa-features-abi msexpand
aconnect mt
acpidbg mt-gnu
add-apt-repository mtr
addpart mtrace
addr2line mtr-packet
airscan-discover mv
alsabat namei
alsaloop nano
...
```
#### `/usr/lib`
```bash
$ ls /usr/lib
apg gvfs pam.d
apparmor hdparm pcmciautils
apt init pcrlock.d
aspell initramfs-tools pm-utils
bfd-plugins ispell policykit-1
binfmt.d kernel polkit-1
brltty klibc pppd
...
```
#### `/usr/share/doc`
```bash
$ ls /usr/share/doc
accountsservice libmpc3
acl libmpcdec6
adduser libmpeg2-4
adwaita-icon-theme libmpfr6
alsa-base libmpg123-0t64
alsa-topology-conf libmsgraph-0-1
alsa-ucm-conf libmtdev1t64
alsa-utils libmtp9t64
amd64-microcode libmtp-common
anacron libmtp-runtime
apg libmutter-14-0
apparmor libmysofa1
apport libnautilus-extension4
apport-core-dump-handler libncurses6
apport-gtk libncursesw6
...
```

### What is the difference between `/bin` and `/usr/bin`?

#### `/bin` (Essential Binaries)
- **Purpose**: Contains essential binaries required for the system to function, especially during boot or when the system is in single-user mode.
- **Availability**: These binaries are available even if the `/usr` directory is not mounted.
- **Usage**: Includes basic commands that are needed for system recovery, maintenance, and basic user interaction.
- **Examples**:
- `ls`: List directory contents
- `cp`: Copy files
- `mv`: Move files
- `cat`: Concatenate and display file contents
- `bash`: The Bourne Again Shell

#### `/usr/bin` (Non-Essential User Binaries)
- **Purpose**: Contains binaries for general use by all users, but these are not essential for booting or repairing the system.
- **Availability**: Typically resides on a separate partition and may not be available if `/usr` is not mounted (e.g., during early boot stages or recovery modes).
- **Usage**: Includes a broader range of applications and tools that are not critical to the core system operation.
- **Examples**:
- `vim`: Text editor
- `gcc`: C compiler
- `python`: Python interpreter
- `git`: Version control system

#### **Historical Context**
- In older UNIX systems, `/bin` was designed for essential commands, while `/usr/bin` held supplementary tools. Over time, `/usr/bin` grew to contain a significant portion of system utilities.
- Modern Linux systems often include `/bin` and `/usr/bin` as part of the same filesystem, and some distributions have unified these directories, **symlinking `/bin` to `/usr/bin`** for simplicity.
-
---

### What is the difference between `/usr/bin` and `/opt`?

#### **`/usr/bin`**
This directory contains user binaries (executable files) that are part of the core system software (not for OS but for system users). These are programs and utilities that are necessary for normal system operations and user tasks. They are typically installed by the distribution's package manager and are shared across all users on the system.

#### **`/opt`**
This directory is used for installing optional software packages that are **not part of the default system installation**. Software in `/opt` is typically self-contained, meaning it may include all necessary libraries and dependencies. It is often used for third-party software or larger applications that don't conform to the standard Linux directory structure. E.g. Google Chromee, Microsoft Edge.

#### Key Differences:
- **Purpose**:
- `/usr/bin` is for essential, system-wide binaries required by the OS and users.
- `/opt` is for optional, third-party software that is installed separately from the core system.

- **Installation**:
- Binaries in `/usr/bin` are generally installed by the system package manager.
- Software in `/opt` is often manually installed or provided by vendors as standalone packages.

---

### `/var` Variable Data
Stores variable and runtime data, like log files in `/var/log`.

```bash
$ ls /var
backups cache crash lib local lock log mail metrics opt run snap spool tmp
```
---

## Additional Important Directories
- `/boot`: Files required for system booting.
- `/dev`: Device files representing hardware.
- `/lib` and `/lib64`: Shared libraries.
- `/lost+found`: Used by the file system to store recovered files after a file system check has been performed.
- `/mnt` and `/media`: Mount points for external file systems or media.
- `/proc` and `/sys`: Virtual filesystems for process and system information.
- `/sbin`: System administration binaries.
- `/srv`: Data served by the system, e.g., web or FTP files.
- `/root`: Home directory for the root user.

---

### Library in Linux:

In Linux, a **library** is a collection of precompiled, reusable code that provides specific functionality for programs. Libraries contain functions or routines that programs can call to perform common tasks, such as handling files, performing mathematical operations, or managing network connections. Rather than each program writing its own code for these tasks, it can instead link to a library, saving time, reducing redundancy, and ensuring consistency across programs.

There are two main types of libraries in Linux:

#### Static Libraries (`.a` files):
These are collections of compiled object files that are embedded directly into the executable at compile time. When a program links to a static library, the library's code becomes part of the program itself, making the executable larger but eliminating the need for the library to be present at runtime.

#### Dynamic Libraries (`.so` files):
These libraries are loaded into memory at runtime when the program is executed. They are not part of the program's executable file but are instead shared by multiple programs. This reduces memory usage because the library is only loaded into memory once. Dynamic libraries can be updated independently of the programs using them, providing greater flexibility.

### Difference Between `/bin` and `/lib`:

#### `/bin` (Binaries):
The `/bin` directory contains **essential system binaries** (executable programs) required for the basic functionality of the system. These are crucial programs that both the operating system and regular users need to perform system tasks. Examples of binaries in `/bin` include commands like `ls`, `cp`, and `mkdir`. These binaries are essential for the system to operate and for users to interact with the system.

#### `/lib` (Libraries):
The `/lib` directory contains **shared libraries** that provide essential support for the binaries in `/bin` (and other directories). These libraries contain the compiled code needed by system programs to execute specific tasks. For example, the C standard library (`libc.so`) is stored in `/lib` and provides fundamental functions like input/output handling and memory management. The files in `/lib` are not executable on their own but are used by the binaries to run efficiently.

#### Key Differences:
- **Purpose**:
- `/bin` contains **executable programs** (binaries) required for system operation.
- `/lib` contains **shared libraries** that provide support for these programs to run.

- **Content**:
- `/bin` holds essential **commands** for both system administrators and regular users.
- `/lib` holds **shared code** that is needed by these commands and other applications to function.

- **Functionality**:
- Programs in `/bin` execute tasks directly, while programs in `/lib` provide the necessary libraries that programs in `/bin` rely on to perform their functions.

---

## Finding binary, source, and manual pages

The `whereis` command in Linux is used to locate the **binary, source, and manual page** files for a command or program. It's a helpful tool for finding the location of executables, their associated documentation, and related source code.

### Syntax:
```bash
whereis [options]
```

### Common Options:
- **`-b`**: Search only for binary files (executable files).
- **`-m`**: Search only for manual pages.
- **`-s`**: Search only for source code.
- **`-u`**: Locate unlinked files (files that don't have a corresponding entry in the database).
- **`-B `**: Specify a directory to search for binaries.
- **`-M `**: Specify a directory to search for manual pages.
- **`-S `**: Specify a directory to search for source files.

### Example Usage:

1. **Locate all files related to the `ls` command**:
```bash
$ whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz
```
This will return locations for the `ls` binary, its manual page, and possibly its source code.

2. **Find the binary for `gcc` only**:
```bash
$ whereis -b gcc
gcc: /usr/bin/gcc /usr/lib/gcc /usr/libexec/gcc /usr/share/gcc
```
This will only return the location of the `gcc` binary.

3. **Find the manual page for `bash`**:
```bash
$ whereis -m bash
bash: /usr/share/man/man1/bash.1.gz
```
This will return the location of the `bash` manual page.

### How It Works:
- The `whereis` command searches through predefined directories set in system configuration files (like `/usr/bin`, `/bin`, `/usr/local/bin`, etc.).
- It uses a database to speed up the process of locating files, unlike the `which` command, which only returns the location of the executable in the directories specified in the `$PATH` environment variable.

### Use Cases:
- Quickly finding the path to an executable, manual page, or source code.
- Verifying whether a specific command or tool is installed on the system.
- Locating specific documentation or source code for a program.

---

## Application Directory Organizatoin Structure

Application directory structures can be organized similar to the operating system's layout. For example, when Apache is installed in `/usr/local`, its directories can look like:
- `/usr/local/apache/bin`: Binaries and executables
- `/usr/local/apache/etc`: Configuration files
- `/usr/local/apache/lib`: Libraries
- `/usr/local/apache/logs`: Log files

If installed in `/opt`, the structure is similar:
- `/opt/apache/bin`: Binaries
- `/opt/apache/etc`: Configurations
- `/opt/apache/lib`: Libraries
- `/opt/apache/logs`: Logs

Another common pattern is separating configuration and log data:
- `/etc/opt/apache`: Configuration files
- `/opt/apache/bin`: Binaries
- `/opt/apache/lib`: Libraries
- `/var/opt/apache`: Logs

Applications can also share common directory spaces. For instance, Apache might be installed in `/usr/local` along with other local applications.

## Summary of Linux Directory Structure

| **Directory** | **Purpose**| **Key Contents**|
|------------------|-----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------|
| `/bin` | Essential binaries for system operation and recovery. | Basic commands like `ls`, `cp`, `mv`, `cat`, `bash`. |
| `/boot` | Contains bootloader files and the kernel. | Kernel images, `grub` configuration files. |
| `/dev` | Device files representing hardware and virtual devices.| Files like `/dev/sda` (disk), `/dev/null`, `/dev/tty` (terminals). |
| `/etc` | System-wide configuration files. | Configs for services like `ssh`, `passwd`, `fstab`. |
| `/home` | User home directories. | Personal files and directories for users (e.g., `/home/naveen`). |
| `/lib` | Essential shared libraries and kernel modules. | Libraries used by programs in `/bin` and `/sbin`. |
| `/media` | Mount points for removable media. | Subdirectories for CDs, USB drives (e.g., `/media/usb`).|
| `/mnt` | Temporary mount point for filesystems. | Used for mounting partitions during maintenance or temporary usage. |
| `/opt` | Optional software packages installed outside standard directories. | Third-party apps like `/opt/google`.|
| `/proc` | Virtual filesystem providing process and system information. | Files like `/proc/cpuinfo`, `/proc/meminfo`.|
| `/root` | Home directory for the root user. | Files specific to the `root` superuser. |
| `/run` | Runtime files like process IDs (PIDs) and sockets.| Files such as `/run/sshd.pid`. |
| `/sbin` | System binaries for administrative tasks. | Commands like `fsck`, `shutdown`, `mount`. |
| `/srv` | Data served by the system, such as web server or FTP server files. | E.g., `/srv/www` for websites. |
| `/sys` | Virtual filesystem for device and system configuration. | Hardware information and control files (e.g., `/sys/class`).|
| `/tmp` | Temporary files, often cleared on reboot. | Session data, temporary downloads. |
| `/usr` | Secondary hierarchy for user programs and data. | Subdirectories like `/usr/bin`, `/usr/lib`, `/usr/share`. |
| `/var` | Variable data files that change during operation. | Logs (`/var/log`), spools (`/var/spool`), caches (`/var/cache`). |

### Notes:
1. Some directories like `/media` or `/mnt` might not have content unless specifically used.
2. On modern systems, certain directories like `/bin` and `/sbin` may be symlinks to `/usr/bin` and `/usr/sbin`.
3. The layout and contents of these directories can vary slightly between Linux distributions.

| Commands | Description |
|-----------------------------------|-------------------------------------------------------------------|
| `ls [dir]`| Lists the contents of a directory.|
| `whereis -b [command]`| Searches for the binary (executable) file of a command. |
| `whereis -m [command]`| Searches for the manual page of a command.|
| `whereis -s [command]`| Searches for the source code of a command.|
| `whereis -u [command]`| Finds unlinked files (files not listed in the system's database). |
| `whereis -B [command]` | Specifies a directory to search for binaries. |
| `whereis -M [command]` | Specifies a directory to search for manual pages. |
| `whereis -S [command]` | Specifies a directory to search for source files. |

This table now includes the `whereis` command, along with its options and descriptions.

---

# Command Line Interface

The **shell** is a program that accepts commands and directs the operating system to execute them. It serves as the interface between the user and the system. The **Command Line Interface (CLI)** is a text-based interface where users type commands.

## Shell and Interface Types
- **CLI (Text Interface)**: When connected to a Linux system, a shell is started, and the user interacts through the command line.
- **GUI (Graphical User Interface)**: When a Linux system is in graphical mode, users interact through a GUI. To access the CLI within a GUI, a terminal emulator (e.g., `xterm`, `GNOME Terminal`) must be used.

## Shell Prompt
The **shell prompt** provides information about the user, system, and current directory. For example:
```bash
sri@envy:~$
```
- `sri`: Username
- `envy`: Hostname
- `~`: Current directory (home directory, e.g., `/home/sri`)

The prompt can vary in format, and users can customize it. Special symbols like `~` (tilde) refer to the user's home directory. For example, `~sri` expands to `/home/sri`.

### Examples of Shell Prompts:
- `[sri@envy /tmp]$`
- `envy:/home/sri>`
- `sri@envy:~>`

Shell prompts can also span multiple lines, showing additional information like time and session details.
```bash
sri@envy:~/Document/Linux
$
```
## What is the difference between terminal and shell?

The terms **terminal** and **shell** are often used interchangeably, but they refer to different components of a Linux or Unix-based system. Here's the distinction:

### Terminal:
- A **terminal** is a program or interface that allows the user to interact with the computer by entering text-based commands. It provides the environment where you can type and execute commands, and it displays the output of those commands.
- **Terminal** is essentially the window or emulator where the user interacts with the system's shell.
- In the past, a **terminal** referred to physical hardware (like a teletype machine or a console), but today, it usually refers to terminal emulator software (like `gnome-terminal`, `xterm`, or `Konsole`) that runs on modern graphical desktop environments.

**Example**: `gnome-terminal`, `xterm`, `Konsole`, etc.

### Shell:
- The **shell** is a program that interprets and executes the commands you type in the terminal. It acts as a command-line interface (CLI) between the user and the operating system.
- The shell processes the commands you type, interprets them, and sends them to the operating system for execution. It also handles tasks like piping commands, file redirection, environment variables, and script execution.
- Common types of shells in Linux include:
- **Bash** (Bourne Again Shell)
- **Zsh** (Z Shell)
- **Fish** (Friendly Interactive Shell)
- **Tcsh** (an enhanced version of the C shell)

**Example**: `bash`, `zsh`, `fish`, `sh`, etc.

### Key Differences:
- **Terminal**:
- The **interface** or **emulator** where commands are entered and output is displayed.
- It's a window or program that allows interaction with the system.

- **Shell**:
- The **program** that interprets and executes commands typed into the terminal.
- It's the command processor that runs inside the terminal and interacts with the operating system.

### Example to Illustrate the Difference:
- When you open a **terminal** (like `gnome-terminal`), you're launching a program that displays a window.
- Inside that terminal window, a **shell** (like `bash`) is running, and it waits for you to type commands.
- When you type a command in the terminal, the **shell** processes and executes it.

In short, the **terminal** is the interface you use to interact with the system, and the **shell** is the program that interprets the commands you input in that interface.

---

# Basic Commands

In Linux, commands are **case-sensitive** and typically in **lowercase**. Items surrounded by square brackets are optional.

## Navigation Commands:
### `pwd` Command
Displays the present working directory.
```bash
# Syntax
$ pwd

# Example
sri@envy:~/Documents/Linux
$ pwd
/home/sri/Documents/Linux
```
### `cd` Command
Changes the current directory to the specified directory. Without an argument, it changes to the home directory.
```bash
# Syntax
$ cd [directory]

# Example
sri@envy:~/Documents/Linux
$ cd /home
sri@envy:/home
$ pwd
/home
```

If you want to go to previous directory use `cd -`, it's like a back button.
```bash
# Syntax
$ cd -

# Example
sri@envy:~
$ cd Documents/Linux/
sri@envy:~/Documents/Linux
$ cd -
/home/sri
sri@envy:~
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$
```

You can get to the user's home directory in **four** differnet ways using `cd`.

```bash
# 1. using "cd"
sri@envy:~/Documents/Linux
$ cd
sri@envy:~
$

# 2. using "cd ~"
sri@envy:~/Documents/Linux
$ cd ~
sri@envy:~
$

# 3. using "cd ~sri"
sri@envy:~/Documents/Linux
$ cd ~sri
sri@envy:~
$

# using "cd /home/sri"
sri@envy:~/Documents/Linux
$ cd /home/sri
sri@envy:~
$
```

## Listing and Viewing Files:
### `ls` Command
Lists the contents of a directory.
```bash
# Syntax
$ ls [path]

# Examples
sri@envy:~
$ ls
Desktop Documents Downloads Music Pictures Public snap Templates Videos
sri@envy:~
$

# Using relative path
sri@envy:~
$ ls Documents/Linux/
Linux_command_line_for_you_and_me_Release_0.1.pdf Linux_Succinctly.pdf README.md
sri@envy:~
$

# Using absolute path
sri@envy:~
$ ls /home/sri/Documents/Linux/
Linux_command_line_for_you_and_me_Release_0.1.pdf Linux_Succinctly.pdf README.md
sri@envy:~
$

```
### `cat` Command
Displays the contents of a **file**.
```bash
# Syntax
$ cat [file]

# Example
sri@envy:~
$ cat /home/sri/Documents/Linux/README.md
# Table of Contents
* [Introduction](#Introduction)
* [Linux Directory Structure](#Linux-Directory-Structure)
* [Summary](#Summary-of-Linux-Directory-Structure)
* [Command Line Interface](#Command-Line-Interface)
* [Basic Commands](#Basic-Commands)
* [Summary](#Summary-of-Basic-Commands)

# Without any arguments
$ cat
This will just repeat whatever I type in standard input.
This will just repeat whatever I type in standard input.
To quit press, Ctrl+c
To quit press, Ctrl+c
^C
sri@envy:~
$
```

## Exiting the Shell:

### `exit` Command
Exit the current shell.
```bash
sri@envy:~
$ exit
```
### `logout` Command
Exit from current login session.
```bash
# Not available in Ubuntu 24.04 Desktop
$ logout
bash: logout: not login shell: use `exit'
```
### `CTRL + d` Shortcut
Exit from shell using the shortcut, `CTRL + d` or `CTRL + D`.
```bash
$ ^D
```

## Command Line Help:
Linux provides built-in documentation through **man** pages, detailing options, example usage and arugments of a specified command.

### `man` Command
Displays the manual page for a command.
```bash
# Syntax
$ man command

# Example
sri@envy:~
$ man ls
```

#### Navigating man pages

| Key | Action |
|-----------------------|-----------------------------|
| Enter, Down Arrow | Move down one line. |
| Up Arrow | Move up one line. |
| Spacebar, Page Down | Move down one page. |
| Page Up | Move up one page. |
| `g` | Go to the start or top. |
| `G` | Go to the end or bottom.|
| `h` | Display help. |
| `j` | Move down one line. |
| `k` | Move up one line. |
| `q` | Quit. |

#### Searching man pages

##### `man -k` Command
Returns all the man pages that contain the **keyword**.
```bash
sri@envy:~
# Syntax
$ man -k [keyword]

# Example
sri@envy:~
$ man -k reboot
grub-reboot (8) - set the default boot entry for GRUB, for the next boot only
halt (8) - Power off, reboot, or halt the machine
poweroff (8) - Power off, reboot, or halt the machine
reboot (2) - reboot or enable/disable Ctrl-Alt-Del
reboot (8) - Power off, reboot, or halt the machine
shutdown (8) - Halt, power off or reboot the machine
systemd-pcrlock-secureboot-authority.service (8) - Analyze and predict TPM2 PCR states and ...
systemd-pcrlock-secureboot-policy.service (8) - Analyze and predict TPM2 PCR states and gen...
systemd-reboot.service (8) - System shutdown logic
systemd-soft-reboot.service (8) - Userspace reboot operation
systemd-sysupdate-reboot.service (8) - Automatically Update OS or Other Resources
systemd-sysupdate-reboot.timer (8) - Automatically Update OS or Other Resources
sri@envy:~
$
```
##### `apropos` Command
Work similar to `man -k [keyword]`.

```bash
# Syntax
$ apropos [keyword]

# Example
sri@envy:~
$ apropos reboot
grub-reboot (8) - set the default boot entry for GRUB, for the next boot only
halt (8) - Power off, reboot, or halt the machine
poweroff (8) - Power off, reboot, or halt the machine
reboot (2) - reboot or enable/disable Ctrl-Alt-Del
reboot (8) - Power off, reboot, or halt the machine
shutdown (8) - Halt, power off or reboot the machine
systemd-pcrlock-secureboot-authority.service (8) - Analyze and predict TPM2 PCR states and ...
systemd-pcrlock-secureboot-policy.service (8) - Analyze and predict TPM2 PCR states and gen...
systemd-reboot.service (8) - System shutdown logic
systemd-soft-reboot.service (8) - Userspace reboot operation
systemd-sysupdate-reboot.service (8) - Automatically Update OS or Other Resources
systemd-sysupdate-reboot.timer (8) - Automatically Update OS or Other Resources
sri@envy:~
$
```

### `--help` option
Displays a help message for a command.
```bash
# Syntax
$ command --help

# Example
sri@envy:~
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
-a, --all do not ignore entries starting with .
-A, --almost-all do not list implied . and ..
--author with -l, print the author of each file
...

sri@envy:~
$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.

Change the current directory to DIR. The default DIR is the value of the
HOME shell variable. If DIR is "-", it is converted to $OLDPWD.

The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
...
```

## Exploring Commands:
You can explore commands in directories like `/bin` and `/usr/bin` using `ls` and `man` to learn their functions.
```bash
sri@envy:~
$ cd /bin
sri@envy:/bin
$ ls
'[' mpris-proxy
aa-enabled mpstat
aa-exec mscompress
aa-features-abi msexpand
aconnect mt
acpidbg mt-gnu
add-apt-repository mtr
addpart mtrace
addr2line mtr-packet
airscan-discover mv
alsabat namei
alsaloop nano
alsamixer nautilus
alsatplg nautilus-autorun-software
alsaucm nautilus-sendto
amidi nawk
amixer nc
apg nc.openbsd
apgbfm neqn
aplay netaddr
sri@envy:/bin
$ man mv
sri@envy:/bin
$
```

### Know what a command does with `whatis`
```bash
# Syntax
$ whatis [command]

# Example
sri@envy:~/Documents
$ whatis ln
ln (1) - make links between files
sri@envy:~/Documents
$ whatis ls
ls (1) - list directory contents
sri@envy:~/Documents
$ whatis cd
cd: nothing appropriate.
sri@envy:~/Documents
$ whatis man
man (1) - an interface to the system reference manuals
sri@envy:~/Documents
$ whatis whatis
whatis (1) - display one-line manual page descriptions
sri@envy:~/Documents
$
```

## Clearing the terminal screen.
Screen can be cleared using

#### `clear` command
The below command clears the entire terminal. Gives a fresh terminal.
```bash
$ clear
```
#### `CTRL + l` Shortcut
This doesn't doesn't clear the terminal, but clears the Window. If you scroll up you can see the previous commands.
```bash
$ ^l
```
---

## Creating files
To create an empty files use `touch`
```bash
# Syntax
$ touch file[s]

# Example
sri@envy:~
$ ls
Desktop Downloads Pictures snap Videos
Documents Music Public Templates
sri@envy:~
$ touch random_file
sri@envy:~
$ ls
Desktop Downloads Pictures random_file Templates
Documents Music Public snap Videos
sri@envy:~down
$ touch random1 randome2
sri@envy:~
$ ls
Desktop Downloads Pictures random1 random_file Templates
Documents Music Public randome2 snap Videos
sri@envy:~
$
```
---

## Executing Dynamic Commands
The `eval` command in Unix/Linux shells is used to execute arguments as a command in the current shell environment. It evaluates the given string or expression, processes it, and then runs the result as a command. This makes it particularly useful in scenarios where commands are dynamically constructed or where special shell syntax needs to be interpreted.

```bash
# Syntax
$ eval [arguments]

# Example
sri@envy:~/Documents/Linux
$ eval "ls -l"
total 3276
-rw-rw-r-- 1 sri sri 734199 Dec 21 17:42 Linux_command_line_for_you_and_me_Release_0.1.pdf
-rw-rw-r-- 1 sri sri 2349921 Dec 21 17:42 Linux_Succinctly.pdf
-rw-rw-r-- 1 sri sri 265126 Jan 4 15:20 README.md
sri@envy:~/Documents/Linux
$
```

### How It Works
1. **First Pass**: `eval` takes its arguments as a single string and processes them.
2. **Second Pass**: The shell then re-evaluates the processed result as a command.

---

### Use Cases
#### Executing Dynamically Constructed Commands:
```bash
sri@envy:~/Documents/Linux
$ cmd="echo Hello, World!"
sri@envy:~/Documents/Linux
$ eval $cmd
Hello, World!
sri@envy:~/Documents/Linux
$ $cmd
Hello, World!
sri@envy:~/Documents/Linux
$
```
Here, `eval` processes the variable `cmd` and executes the resulting command: `echo Hello, World!`.

### Setting Environment Variables:
For example, starting the SSH agent:
```bash
sri@envy:~
$ eval "$(ssh-agent -s)"
SSH_AUTH_SOCK=/tmp/ssh-abc12345/agent.1234; export SSH_AUTH_SOCK;
SSH_AGENT_PID=1234; export SSH_AGENT_PID;
echo Agent pid 1234;
```
The `ssh-agent -s` outputs commands to set environment variables, and `eval` ensures those commands are executed in the current shell.

### Combining Multiple Commands:
If you construct a command dynamically and need the shell to interpret it fully:
```bash
$ command="ls -l | grep 'myfile'"
$ eval $command
```
---

### Why Use `eval`?
- It allows you to execute commands that are dynamically generated or stored in variables.
- It interprets and executes complex shell expressions that require multiple levels of processing.

---

### Caution
The `eval` command can be risky if used with untrusted input, as it can execute unintended or malicious commands. For example:
```bash
input='rm -rf /'
eval $input # Dangerous!
```
Always sanitize or validate input before passing it to `eval`.

---

## Summary of Basic Commands

| Command| Description |
|------------------------|-------------|
| `pwd` | Displays the present working directory. |
| `cd [directory]` | Changes the current directory to the specified directory. |
| `cd -` | Changes to the previous directory. |
| `cd` | Changes to the user's home directory. |
| `cd ~` | Changes to the user's home directory. |
| `cd ~user` | Changes to the home directory of the user `user`. |
| `cd /home/user` | Changes to the directory `/home/user`. |
| `ls [path]`| Lists the contents of the specified path. |
| `ls` | Lists the contents of the current directory. |
| `cat [file]` | Displays the contents of a specified file. |
| `cat` | Reads from the standard input and displays the input. |
| `exit` | Exits the current shell. |
| `logout` | Exits the current login session (not available in all shells). |
| `^D` or `^d` | Exits the shell using the shortcut `CTRL+D`. |
| `man command`| Displays the manual page for a command. |
| `man -k keyword` | Returns all man pages containing the specified keyword. |
| `apropos keyword`| Searches for the keyword in the manual page descriptions. |
| `[command] --help` | Displays a help message for the specified command. |
| `whatis [command]`| Display one-line manual page descriptions |
| `clear`| Clears the entire terminal screen. |
| `^L` or `^l` | Clears the terminal window (history still accessible via scroll). |
| `touch file(s)` | Creates empty file(s). |
| `eval [arguments]` | Executes the command in arguments. |

### Navigating man pages

| Key | Action |
|----------------------|--------------------------------------|
| Enter, Down Arrow | Move down one line. |
| Up Arrow, `k` | Move up one line. |
| Spacebar, Page Down | Move down one page. |
| `g` | Go to the start or top. |
| `G` | Go to the end or bottom.|
| `h` | Display help. |
| `j` | Move down one line. |
| `k` | Move up one line. |
| `l` | Move right (scroll horizontally). |
| `q` | Quit. |

---

# Directories
In linux, we call **folder** as **directory**. In Linux, directories end with a trailing forward slash.

## Absolute vs Relative Paths
### Absolute Path:
Starts with a `/` and points to a location from the root of the file system.
```bash
sri@envy:~/Documents/Linux
$ cd /home/sri/Music/
sri@envy:~/Music
$
```

### Relative Path:
Doesn't start with a `/` and is relative to the current working directory.
```bash
sri@envy:~/Documents/Linux
$ cd ../../Music/
sri@envy:~/Music
$
```

## Home Directory
There are many ways to go to user's home directory from anywhere.
```bash
# 1. using "cd"
sri@envy:~/Documents/Linux
$ cd
sri@envy:~
$

# 2. using "cd ~"
sri@envy:~/Documents/Linux
$ cd ~
sri@envy:~
$

# 3. using "cd ~sri"
sri@envy:~/Documents/Linux
$ cd ~sri
sri@envy:~
$

# using "cd /home/sri"
sri@envy:~/Documents/Linux
$ cd /home/sri
sri@envy:~
$
```

## Special Directory References
- `.` represents the **current directory**.
```bash
# Syntax
$ cd . # Stays in the current directory

# Example
sri@envy:~/Documents/Linux
$ cd .
sri@envy:~/Documents/Linux
$
```

- `..` represents the **parent directory**.
```bash
# Syntax
$ cd .. # Moves up one level to the parent directory

# Example
sri@envy:~/Documents/Linux
$ cd ..
sri@envy:~/Documents
$
```

## Navigating Directories
### Change directories using `cd`:
```bash
# Syntax
$ cd [directory]

# Example
sri@envy:~/Documents/Linux
$ cd ~/Music/
sri@envy:~/Music
$ pwd
/home/sri/Music
sri@envy:~/Music
$
```

### Return to the previous directory with `cd -`:
```bash
# Syntax:
$ cd -

# Example
sri@envy:~/Documents/Linux
$ cd ~/Music/
sri@envy:~/Music
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$
```

Note using `cd .` affects the navigation of `cd -`.
```bash
sri@envy:~
$ cd ~/Documents/Linux/ # going to Linux
sri@envy:~/Documents/Linux
$ cd - # going to home
/home/sri
sri@envy:~
$ cd - # going to Linux
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ cd . # Staying in Linux
sri@envy:~/Documents/Linux
$ cd - # Staying in Linux itself
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$

# Internally uses $OLDPWD
# When you use "cd .",
# $OLDPWD gets modified.

sri@envy:~
$ cd ~/Documents/Linux/
sri@envy:~/Documents/Linux
$ echo $OLDPWD
/home/sri
sri@envy:~/Documents/Linux
$ cd -
/home/sri
sri@envy:~
$ echo $OLDPWD
/home/sri/Documents/Linux
sri@envy:~
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ echo $OLDPWD
/home/sri
sri@envy:~/Documents/Linux
$ cd .
sri@envy:~/Documents/Linux
$ echo $OLDPWD
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$ cd -
/home/sri/Documents/Linux
sri@envy:~/Documents/Linux
$
```
The loop happens because `cd -` toggles between the current directory and the last visited directory. When you use `cd .`, it doesn't change the directory, so the "previous directory" remains the same. Repeatedly using `cd -` in the same location keeps toggling to the same directory, causing the apparent loop.

## Creating and Removing Directories
### Create a directory with `mkdir`:
```bash
# Syntax
$ mkdir newdir # Creates a new directory called newdir

# Example
sri@envy:~/Desktop
$ ls
sri@envy:~/Desktop
$ mkdir dir
sri@envy:~/Desktop
$ ls
dir
sri@envy:~/Desktop
$ ls -ld dir
drwxrwxr-x 2 sri sri 4096 Jan 1 12:00 dir
sri@envy:~/Desktop
$
```

### Create directories with `mkdir -p` (including intermediate directories):
```bash
# Syntax
$ mkdir -p newdir/one/two # Creates newdir, then one, and then two inside it

# Example
sri@envy:~/Desktop
$ ls
sri@envy:~/Desktop
$ mkdir dir/sub-dir/sub-sub-dir
mkdir: cannot create directory ‘dir/sub-dir/sub-sub-dir': No such file or directory
sri@envy:~/Desktop
$ mkdir -p dir/sub-dir/sub-sub-dir
sri@envy:~/Desktop
$ tree dir
dir
└── sub-dir
└── sub-sub-dir

3 directories, 0 files
sri@envy:~/Desktop
$

```

### Remove an empty directory with `rmdir`:
```bash
# Syntax
$ rmdir newdir # Removes the empty directory newdir

# Example
sri@envy:~/Desktop
$ ls
dir
sri@envy:~/Desktop
$ ls -l dir # Empty directory
total 0
sri@envy:~/Desktop
$ rmdir dir
sri@envy:~/Desktop
$ ls
sri@envy:~/Desktop
$

sri@envy:~/Desktop
$ ls
dir
sri@envy:~/Desktop
$ ls -l dir # Empty directory
total 0
sri@envy:~/Desktop
$ rm -r dir
sri@envy:~/Desktop
$ ls
sri@envy:~/Desktop
$

```

### Forcefully remove a directory and its contents with `rm -rf`:

Consider this setup to demonstrate the need for forcefull removal of directory. We creating a temporary git repository.
```bash
sri@envy:~/Desktop
$ mkdir temp_repo
sri@envy:~/Desktop
$ cd temp_repo/
sri@envy:~/Desktop/temp_repo
$ touch a
sri@envy:~/Desktop/temp_repo
$ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m
Initialized empty Git repository in /home/sri/Desktop/temp_repo/.git/
sri@envy:~/Desktop/temp_repo
$ git add .
sri@envy:~/Desktop/temp_repo
$ git commit -m "sample commit"
[master (root-commit) 681a648] sample commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 a
```

Now, let's try to delete this directory with `rm -r`
```bash
sri@envy:~/Desktop/temp_repo
$ cd ..
sri@envy:~/Desktop
$ rm -r temp_repo/
rm: remove write-protected regular file 'temp_repo/.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391'?
```
There will be lot of warnings, requesting us about deletion. The input `y` has to be given repeatedly to delete the directory entirely. Here is where `-f` option comes in, it allows us to delete the directory in one go, without any warnings. But this can be dangerous, since there is **no reversion** of a wrong delete.

```bash
# Syntax
$ rm -rf newdir # Deletes the newdir directory and all of its contents FORCEFULLY

# Example
sri@envy:~/Desktop
$ rm -rf temp_repo/
sri@envy:~/Desktop
$
```

## Summary of Directory Commands

| Command | Description |
|--------------------------|-------------------------------------------------------------------------------------------------------|
| `cd [directory]` | Changes the current directory to the specified directory.|
| `cd -` | Returns to the previous directory. |
| `cd` | Changes to the home directory. |
| `cd ~` | Changes to the home directory (shortcut).|
| `cd ~[username]` | Changes to the home directory of the specified user. |
| `cd /home/[username]`| Changes to the absolute path of the specified user's home directory. |
| `cd .` | Stays in the current directory. |
| `cd ..` | Moves up one level to the parent directory. |
| `mkdir [directory]` | Creates a new directory with the specified name. |
| `mkdir -p [path]`| Creates nested directories, including intermediate ones, if they don't exist.|
| `rmdir [directory]` | Removes an empty directory. |
| `rm -r [directory]` | Removes a directory and its contents recursively, prompting for confirmation for protected files.|
| `rm -rf [directory]` | Removes a directory and its contents forcefully, without any prompts or confirmation.|
| `pwd`| Displays the present working directory. |
| `ls [path]` | Lists the contents of the specified directory. |
| `ls` | Lists the contents of the current directory.|
| `tree [directory]` | Displays the directory structure in a tree format. |
| `touch [file]` | Creates an empty file with the specified name. |
| `git init` | Initializes a new Git repository in the current directory. |
| `git add .` | Stages all changes in the current directory for the next commit. |
| `git commit -m [message]`| Creates a commit with the specified message. |

---

# Viewing File and Directory Details

In Linux, the `ls` command is used to list files and directories, but it can also provide detailed information about them when combined with different options.

## Basic `ls` Command

The `ls` command by itself will simply list the files and directories in the current directory:
```bash
# Syntax
$ ls

# Example
sri@envy:~
$ ls
Desktop Documents Downloads Music Pictures Public snap Templates Videos
sri@envy:~
$
```

### Using `ls -l` for Detailed Listings

The `ls -l` command provides a long listing format that shows detailed information about files and directories.

```bash
# Syntax
$ ls -l

# Example
sri@envy:~
$ ls -l
total 36
drwxr-xr-x 2 sri sri 4096 Jan 1 12:11 Desktop
drwxr-xr-x 13 sri sri 4096 Dec 29 18:04 Documents
drwxr-xr-x 2 sri sri 4096 Dec 31 20:15 Downloads
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music
drwxr-xr-x 3 sri sri 4096 Dec 23 15:41 Pictures
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Public
drwx------ 8 sri sri 4096 Dec 31 18:07 snap
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Templates
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Videos
sri@envy:~
$
```

### Breakdown of `ls -l` Output

Each line in the output contains several columns with specific information:

| **Field** | **Description** | **Example**|
|------------------------|----------------------------------------------------------|------------------------|
| **Permissions** | Indicates file type and access permissions. | `drwxr-xr-x` |
| **Links** | Number of hard links to the file or directory. | `2`|
| **Owner** | Name of the user who owns the file or directory.| `sri` |
| **Group** | Group associated with the file or directory.| `sri` |
| **File Size** | Size of the file in bytes. | `4096` |
| **Modification Time** | Last modification date and time.| `Jan 1 12:11` |
| **Name**| Name of the file or directory. | `Desktop` |

---

### Example Breakdown

For a specific file:
```bash
-rw-r--r-- 1 sri sri 512 Dec 31 21:00 shopping-list.txt
drwxr-xr-x 13 sri sri 4096 Dec 29 18:04 Documents

```

| **Field** | **Value** | **Explanation** |
|------------------------|---------------------|-----------------------------------------------------|
| **Permissions** | `drwxr-xr-x` | Regular directory with read/write/execute for owner, read and execute for group and others. |
| **Links** | `13`| Single hard link.|
| **Owner** | `sri` | File is owned by the user `sri`.|
| **Group** | `sri` | Associated group is `sri`.|
| **File Size** | `4096` | File is 4096 bytes in size.|
| **Modification Time**| `Dec 29 18:04`| File was last modified on Dec 31 at 9:00 PM.|
| **Name**| `Document`| Name of the directory is `Document`.|

## Displaying Hidden Files

By default, `ls` does not show hidden files (files that begin with a dot `.`). To display hidden files, use the `-a` option:
```bash
# Syntax
$ ls -a

# Example
sri@envy:~
$ ls -a
. .cache .gnupg Public .vim
.. .config .lesshst .python_history .viminfo
.aspell.en.prepl Desktop .local snap .vimrc
.aspell.en.pws Documents Music .ssh .vscode
.bash_history .dotnet Pictures .sudo_as_admin_successful
.bash_logout Downloads .pki Templates
.bashrc .gitconfig .profile Videos
sri@envy:~
$
```

To list hidden files with details, use both the `-a` and `-l` options:

```bash
sri@envy:~
$ ls -al
total 164
drwxr-x--- 20 sri sri 4096 Jan 1 11:58 .
drwxr-xr-x 3 root root 4096 Dec 30 14:41 ..
-rw-rw-r-- 1 sri sri 24 Dec 30 18:03 .aspell.en.prepl
-rw-rw-r-- 1 sri sri 183 Dec 30 18:03 .aspell.en.pws
-rw------- 1 sri sri 25677 Jan 1 07:14 .bash_history
-rw-r--r-- 1 sri sri 220 Mar 31 2024 .bash_logout
-rw-r--r-- 1 sri sri 4316 Dec 29 18:48 .bashrc
drwx------ 19 sri sri 4096 Dec 25 20:21 .cache
drwx------ 23 sri sri 4096 Dec 31 16:12 .config
drwxr-xr-x 2 sri sri 4096 Jan 1 12:11 Desktop
drwxr-xr-x 13 sri sri 4096 Dec 29 18:04 Documents
drwxrwxr-x 3 sri sri 4096 Dec 21 17:15 .dotnet
drwxr-xr-x 2 sri sri 4096 Dec 31 20:15 Downloads
-rw-rw-r-- 1 sri sri 152 Dec 21 17:40 .gitconfig
drwx------ 2 sri sri 4096 Jan 1 11:50 .gnupg
-rw------- 1 sri sri 90 Jan 1 11:58 .lesshst
drwx------ 4 sri sri 4096 Dec 21 16:45 .local
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music
drwxr-xr-x 3 sri sri 4096 Dec 23 15:41 Pictures
drwx------ 3 sri sri 4096 Dec 21 17:15 .pki
-rw-r--r-- 1 sri sri 807 Mar 31 2024 .profile
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Public
-rw------- 1 sri sri 329 Dec 31 12:34 .python_history
drwx------ 8 sri sri 4096 Dec 31 18:07 snap
drwx------ 2 sri sri 4096 Dec 21 17:29 .ssh
-rw-r--r-- 1 sri sri 0 Dec 21 16:45 .sudo_as_admin_successful
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Templates
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Videos
drwxr-xr-x 2 sri sri 4096 Dec 27 20:42 .vim
-rw------- 1 sri sri 15521 Dec 31 11:22 .viminfo
-rw-rw-r-- 1 sri sri 1260 Dec 26 10:43 .vimrc
drwxrwxr-x 4 sri sri 4096 Dec 21 17:15 .vscode
sri@envy:~
$
```

## Colorized Output with `--color`

To add color to the `ls` output, use the `--color` option. This is **present by default**. This helps differentiate file types:
```bash
# Syntax
$ ls --color
```

## File Type Indicators with `-F`

The `-F` option appends a symbol to each file or directory to indicate its type. Here's how it works:
```bash
# Syntax
$ ls -aF

# Example
sri@envy:~
$ ls -aF
./ .config/ .local/ .sudo_as_admin_successful
../ Desktop/ Music/ Templates/
a.out* Documents/ Pictures/ Videos/
.aspell.en.prepl .dotnet/ .pki/ .vim/
.aspell.en.pws Downloads/ .profile .viminfo
.bash_history .gitconfig Public/ .vimrc
.bash_logout .gnupg/ .python_history .vscode/
.bashrc hello.c snap/
.cache/ .lesshst .ssh/
sri@envy:~
$
```

For a long listing with file type indicators:
```bash
# Syntax
$ ls -alf

sri@envy:~
$ ls -alF
total 184
drwxr-x--- 20 sri sri 4096 Jan 1 13:20 ./
drwxr-xr-x 3 root root 4096 Dec 30 14:41 ../
-rwxrwxr-x 1 sri sri 15960 Jan 1 13:20 a.out*
-rw-rw-r-- 1 sri sri 24 Dec 30 18:03 .aspell.en.prepl
-rw-rw-r-- 1 sri sri 183 Dec 30 18:03 .aspell.en.pws
-rw------- 1 sri sri 25677 Jan 1 07:14 .bash_history
-rw-r--r-- 1 sri sri 220 Mar 31 2024 .bash_logout
-rw-r--r-- 1 sri sri 4316 Dec 29 18:48 .bashrc
drwx------ 19 sri sri 4096 Dec 25 20:21 .cache/
drwx------ 23 sri sri 4096 Dec 31 16:12 .config/
drwxr-xr-x 2 sri sri 4096 Jan 1 12:11 Desktop/
drwxr-xr-x 13 sri sri 4096 Dec 29 18:04 Documents/
drwxrwxr-x 3 sri sri 4096 Dec 21 17:15 .dotnet/
drwxr-xr-x 2 sri sri 4096 Dec 31 20:15 Downloads/
-rw-rw-r-- 1 sri sri 152 Dec 21 17:40 .gitconfig
drwx------ 2 sri sri 4096 Jan 1 11:50 .gnupg/
-rw-rw-r-- 1 sri sri 72 Jan 1 13:20 hello.c
-rw------- 1 sri sri 90 Jan 1 11:58 .lesshst
drwx------ 4 sri sri 4096 Dec 21 16:45 .local/
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music/
drwxr-xr-x 3 sri sri 4096 Dec 23 15:41 Pictures/
drwx------ 3 sri sri 4096 Dec 21 17:15 .pki/
-rw-r--r-- 1 sri sri 807 Mar 31 2024 .profile
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Public/
-rw------- 1 sri sri 329 Dec 31 12:34 .python_history
drwx------ 8 sri sri 4096 Dec 31 18:07 snap/
drwx------ 2 sri sri 4096 Dec 21 17:29 .ssh/
-rw-r--r-- 1 sri sri 0 Dec 21 16:45 .sudo_as_admin_successful
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Templates/
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Videos/
drwxr-xr-x 2 sri sri 4096 Dec 27 20:42 .vim/
-rw------- 1 sri sri 14641 Jan 1 13:20 .viminfo
-rw-rw-r-- 1 sri sri 1260 Dec 26 10:43 .vimrc
drwxrwxr-x 4 sri sri 4096 Dec 21 17:15 .vscode/
sri@envy:~
$
```

Here's a list of file type indicators used in Linux with the `ls` command:

| **Symbol in Permission String** | **File Type** | **Description** | **Default Color** |
|------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------|
| `-`| Regular file | Standard files that contain data, such as text, images, videos, or executables.| Default (white) |
| `b`| Block special file | Files that represent hardware devices capable of data storage, such as hard drives or USB drives, accessed in fixed-size blocks. | Yellow with bold|
| `c`| Character special file | Files that represent hardware devices, such as keyboards or terminals, accessed character by character. Interfaces with devices that transfer data in streams. | Yellow with bold|
| `d`| Directory| Containers for files and other directories, forming a hierarchical structure in the file system. | Blue|
| `l`| Symbolic link| Special files that act as shortcuts, pointing to another file or directory.| Cyan (light blue) |
| `p`| FIFO (named pipe)| Used in IPC. Files that act as conduits, allowing two processes to communicate by writing and reading data in a first-in, first-out (FIFO) order. | Yellow (brown) |
| `s`| Socket | Special files used for inter-process communication (IPC), typically for network services or local socket connections. Enables bidirectional communication. | Magenta (purple)|
| `?`| Unknown file type| Files that do not match any recognized file type. | N/A |
| `*`| Executable | Files that can be executed as programs or scripts.| Green |
| `/`| Directory (Indicator)| Indicates a directory in file listings. | Blue|
| `@`| Symlink (Symbolic link) | Indicates a symbolic link in file listings. | Cyan (light blue) |
| `=`| Socket (Indicator) | Indicates a socket in file listings. | Magenta (purple)|
| `\|` | Named pipe (FIFO) (Indicator) | Indicates a named pipe in file listings. | Yellow (brown) |

### Notes
The colors shown above are defaults in most Linux distributions. These may vary based on user configuration (`~/.bashrc`, `~/.zshrc`) or terminal settings. - Colors can be customized using the `LS_COLORS` environment variable. To check the current configuration, run:
```bash
sri@envy:~
$ echo $LS_COLORS
rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=00:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:
```
The `$LS_COLORS` variable defines the colors and styles for file types and extensions in `ls --color` output. It's a series of `key=value` pairs separated by colons (`:`):

- **Keys**: File types (`di`=directory, `ln`=symlink, `pi`=pipe, etc.) or extensions (`*.tar`, `*.zip`).
- **Values**: Style codes (`00`=default, `01`=bold) and colors (`31`=red, `34`=blue, `40`=black background, etc.).

### Examples
- `di=01;34`: Directories are bold blue.
- `ln=01;36`: Symlinks are bold cyan.
- `*.tar=01;31`: `.tar` files are bold red.

Customize with `dircolors` or directly export a new `LS_COLORS` value:
```bash
$ export LS_COLORS="di=01;32:ln=01;33"
```

## Symbolic Links

A **symbolic link** (also known as a symlink or soft link) is a special type of file in Linux that points to another file or directory. It acts as a shortcut, redirecting access to the original target file or directory.

### Characteristics of Symbolic Links:
- **Independent from the target:** If the target file or directory is moved or deleted, the symlink becomes "broken," but the symlink itself remains.
- **Flexible:** Can link to files or directories located anywhere in the file system, including remote locations.
- **Different inode:** The symlink has its own inode, separate from the target file.

### Creating a Symbolic Link
Use the `ln -s` command to create a symbolic link:
```bash
# Syntax:
$ ln -s [target] [symlink]

# Example:
sri@envy:~/Desktop
$ ln -s /home/sri/Documents/myfile.txt myfilelink
sri@envy:~/Desktop
$ ls -F
myfilelink@
sri@envy:~/Desktop
$
```
This creates a symbolic link `myfilelink` that points to `/home/sri/Documents/myfile.txt`.

### Viewing Symbolic Links
Use the `ls -l` command to identify symbolic links. The symlink is indicated with an `@` in `ls -F` or displayed with an arrow (`->`) pointing to the target:
```bash
# Syntax
$ ls -lF

# Example
sri@envy:~/Desktop
$ ls -alF
total 8
drwxr-xr-x 2 sri sri 4096 Jan 1 13:30 ./
drwxr-x--- 20 sri sri 4096 Jan 1 13:25 ../
lrwxrwxrwx 1 sri sri 30 Jan 1 13:30 myfilelink -> /home/sri/Documents/myfile.txt
sri@envy:~/Desktop
$
```

### Using a Symbolic Link
You can use a symbolic link just like the original file or directory. For example:
- **Open the linked file:**
```bash
sri@envy:~/Desktop
$ cat myfilelink
This is myfile.txt
sri@envy:~/Desktop
$
```
- **Navigate to a linked directory:**
```bash
$ cd mydirlink
```

### Managing Symbolic Links
- **Remove a symlink:** Use the `rm` command (this removes only the symlink, not the target):
```bash
$ rm mylink
```
- **Edit or recreate a symlink:** Re-run the `ln -s` command with the desired target.

### Broken Symlinks
A symlink becomes "broken" if the target is moved or deleted. You can identify broken symlinks with:
```bash
$ ls -l
sri@envy:~/Desktop
$ ls -l
total 0
lrwxrwxrwx 1 sri sri 30 Jan 1 13:30 myfilelink -> /home/sri/Documents/myfile.txt (red font and highlighted)
```

Symbolic links are commonly used for tasks such as creating shortcuts, linking configuration files, or managing library paths efficiently.

## Sorting Files by Time

To list files sorted by their modification time, use the `-t` option:
```bash
# Syntax
$ ls -t

# Example
sri@envy:~
$ ls -alt
total 168
drwxr-xr-x 2 sri sri 4096 Jan 1 13:36 Desktop
drwxr-xr-x 13 sri sri 4096 Jan 1 13:35 Documents
drwxr-x--- 20 sri sri 4096 Jan 1 13:25 .
-rw------- 1 sri sri 16617 Jan 1 13:25 .viminfo
-rw------- 1 sri sri 90 Jan 1 11:58 .lesshst
drwx------ 2 sri sri 4096 Jan 1 11:50 .gnupg
-rw------- 1 sri sri 25677 Jan 1 07:14 .bash_history
drwxr-xr-x 2 sri sri 4096 Dec 31 20:15 Downloads
drwx------ 8 sri sri 4096 Dec 31 18:07 snap
drwx------ 23 sri sri 4096 Dec 31 16:12 .config
-rw------- 1 sri sri 329 Dec 31 12:34 .python_history
-rw-rw-r-- 1 sri sri 24 Dec 30 18:03 .aspell.en.prepl
-rw-rw-r-- 1 sri sri 183 Dec 30 18:03 .aspell.en.pws
drwxr-xr-x 3 root root 4096 Dec 30 14:41 ..
-rw-r--r-- 1 sri sri 4316 Dec 29 18:48 .bashrc
drwxr-xr-x 2 sri sri 4096 Dec 27 20:42 .vim
-rw-rw-r-- 1 sri sri 1260 Dec 26 10:43 .vimrc
drwx------ 19 sri sri 4096 Dec 25 20:21 .cache
drwxr-xr-x 3 sri sri 4096 Dec 23 15:41 Pictures
-rw-rw-r-- 1 sri sri 152 Dec 21 17:40 .gitconfig
drwx------ 2 sri sri 4096 Dec 21 17:29 .ssh
drwxrwxr-x 3 sri sri 4096 Dec 21 17:15 .dotnet
drwxrwxr-x 4 sri sri 4096 Dec 21 17:15 .vscode
drwx------ 3 sri sri 4096 Dec 21 17:15 .pki
-rw-r--r-- 1 sri sri 0 Dec 21 16:45 .sudo_as_admin_successful
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Public
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Templates
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Videos
drwx------ 4 sri sri 4096 Dec 21 16:45 .local
-rw-r--r-- 1 sri sri 220 Mar 31 2024 .bash_logout
-rw-r--r-- 1 sri sri 807 Mar 31 2024 .profile
sri@envy:~
$
```
To reverse the order (show the oldest files first), use `-r`:
```bash
# Syntax
$ ls -lr

# Example
sri@envy:~
$ ls -altr
total 168
-rw-r--r-- 1 sri sri 807 Mar 31 2024 .profile
-rw-r--r-- 1 sri sri 220 Mar 31 2024 .bash_logout
drwx------ 4 sri sri 4096 Dec 21 16:45 .local
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Videos
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Templates
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Public
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music
-rw-r--r-- 1 sri sri 0 Dec 21 16:45 .sudo_as_admin_successful
drwx------ 3 sri sri 4096 Dec 21 17:15 .pki
drwxrwxr-x 4 sri sri 4096 Dec 21 17:15 .vscode
drwxrwxr-x 3 sri sri 4096 Dec 21 17:15 .dotnet
drwx------ 2 sri sri 4096 Dec 21 17:29 .ssh
-rw-rw-r-- 1 sri sri 152 Dec 21 17:40 .gitconfig
drwxr-xr-x 3 sri sri 4096 Dec 23 15:41 Pictures
drwx------ 19 sri sri 4096 Dec 25 20:21 .cache
-rw-rw-r-- 1 sri sri 1260 Dec 26 10:43 .vimrc
drwxr-xr-x 2 sri sri 4096 Dec 27 20:42 .vim
-rw-r--r-- 1 sri sri 4316 Dec 29 18:48 .bashrc
drwxr-xr-x 3 root root 4096 Dec 30 14:41 ..
-rw-rw-r-- 1 sri sri 183 Dec 30 18:03 .aspell.en.pws
-rw-rw-r-- 1 sri sri 24 Dec 30 18:03 .aspell.en.prepl
-rw------- 1 sri sri 329 Dec 31 12:34 .python_history
drwx------ 23 sri sri 4096 Dec 31 16:12 .config
drwx------ 8 sri sri 4096 Dec 31 18:07 snap
drwxr-xr-x 2 sri sri 4096 Dec 31 20:15 Downloads
-rw------- 1 sri sri 25677 Jan 1 07:14 .bash_history
drwx------ 2 sri sri 4096 Jan 1 11:50 .gnupg
-rw------- 1 sri sri 90 Jan 1 11:58 .lesshst
-rw------- 1 sri sri 16617 Jan 1 13:25 .viminfo
drwxr-x--- 20 sri sri 4096 Jan 1 13:25 .
drwxr-xr-x 13 sri sri 4096 Jan 1 13:35 Documents
drwxr-xr-x 2 sri sri 4096 Jan 1 13:36 Desktop
sri@envy:~
$
```

## Recursive Listing with `-R`

To list all files and directories recursively, use the `-R` option:
```bash
# Syntax
$ ls -R
.:
Desktop Documents Downloads link-to-to-do Music program to-do.txt

./Desktop:
...

./Documents:
cat.jpg report.txt

./Downloads:
...

./Music:
JohnColtrane

./Music/JohnColtrane:
giant-steps.mp3
```

## Working with Directories Using `-d`

If you want to list the **directory itself** (without showing its contents), use the `-d` option:
```bash
# Syntax
$ ls -d [Directory]

# Example
sri@envy:~
$ ls -d Music/
Music/
sri@envy:~
$ ls -ld Music/
drwxr-xr-x 2 sri sri 4096 Dec 21 16:45 Music/
sri@envy:~
$
```

## Escaping Special Characters in Filenames

Files or directories with spaces or special characters in their names require special handling. You can either **use quotes** or **escape the characters with a backslash** (`\ ` - escapes the whitespace).

```bash
# Syntax
$ ls "file name with space"
$ ls file\ name\ with\ space

# Example
sri@envy:~
$ touch "my to do list"
sri@envy:~
$ ls -b
Desktop Downloads my\ to\ do\ list Public Templates
Documents Music Pictures snap Videos
sri@envy:~
$ ls -l my\ to\ do\ list
-rw-rw-r-- 1 sri sri 0 Jan 1 14:11 'my to do list'
sri@envy:~
$ ls -l "my to do list"
-rw-rw-r-- 1 sri sri 0 Jan 1 14:11 'my to do list'
sri@envy:~
$
```

### Using `-b` to View Escaped Names:
```bash
# Syntax
$ ls -b

# Example
sri@envy:~
$ ls -b
Desktop Downloads my\ to\ do\ list Public Templates
Documents Music Pictures snap Videos
sri@envy:~
$
```

## Tree Command for Visual Directory Structure

The `tree` command provides a more visually appealing way to view directory structures.

`tree` is not installed by default:
```bash
$ sudo apt install tree
```

You can use it as follows:
```bash
# Syntax
$ tree
.
|-- Desktop
|-- Documents
| |-- cat.jpg
| |-- report.txt
|-- Downloads
|-- Music
| |-- JohnColtrane
| |-- giant-steps.mp3
|-- program
|-- to-do.txt
5 directories, 6 files
```

For only directories, use `-d`:
```bash
# Syntax
$ tree -d
.
|-- Desktop
|-- Documents
|-- Downloads
|-- Music
|-- JohnColtrane
5 directories

# Example
sri@envy:~
$ tree -d
.
├── Desktop
├── Documents
│   ├── Git
│   ├── Introduction-to-Vedanta
│   │   ├── Audio
│   │   └── Summary
│   ├── Linux
│   ├── Markdown
│   ├── Nitya-Karma
│   │   ├── Sandhyavandanam
│   │   ├── Shlokas
│   │   └── Stotrams
│   │   ├── Hanuman_Chalisa
│   │   ├── Nama_Ramayanam
│   │   └── Vishnu_Sahasranamam
│   ├── Power-Of-Posture
│   ├── Python
│   ├── Python-DSA
│   │   ├── Chapter-01
│   │   │   └── Question-10
│   │   │   └── __pycache__
│   │   ├── Chapter-02
│   │   │   ├── Programming-Exercises
│   │   │   ├── Self-Check
│   │   │   └── TimeitExperiments
│   │   ├── Chapter-03
│   │   │   ├── Deque
│   │   │   │   └── __pycache__
```

To colorize the output, use `-C` (by deafult this option is used):
```bash
# Syntax
$ tree -C
```

## Summary of Viewing File and Directory Commands
| Command | Description |
|---------------------------------|----------------------------------------------------------------------------------------------|
| `ls` | Lists files and directories in the current directory.|
| `ls -l` | Lists files and directories with detailed information (long format).|
| `ls -a` | Lists all files, including hidden files (starting with `.`).|
| `ls --color` | Displays files with color-coded output (for file types).|
| `ls -F` | Appends indicators (e.g., `/` for directories, `*` for executables) to file names. |
| `ls -t` | Lists files sorted by modification time (most recent first).|
| `ls -r` | Reverses the order of the file list.|
| `ls -R` | Recursively lists all files and directories.|
| `ls -d [Directory]` | Displays information about directories, not their contents. |
| `ls "file name with space"` | Lists a file with spaces in its name by enclosing it in quotes. |
| `ls file\ name\ with\ space` | Lists a file with spaces in its name by escaping spaces with a backslash (`\`). |
| `ls -b` | Displays file names with non-printable characters as escape sequences. |
| `ls -alf` | Combines options: lists all files, including hidden ones, in long format. |
| `ls -altr`| Lists all files, including hidden ones, in long format, sorted by time in reverse order.|
| `echo $LS_COLORS` | Displays the current color settings for the `ls` command. |
| `export LS_COLORS="di=01;32:ln=01;33"` | Customizes the `ls` color scheme (e.g., green for directories, yellow for links). |
| `ln -s [target] [symlink]`| Creates a symbolic link named `[symlink]` pointing to `[target]`. |
| `cat myfilelink` | Displays the contents of the file pointed to by the symbolic link `myfilelink`. |
| `cd mydirlink`| Changes the current directory to the one pointed to by the symbolic link `mydirlink`. |
| `tree`| Displays the directory structure as a tree.|
| `tree -d` | Displays only directories in the tree structure. |
| `tree -C` | Displays the tree structure with color-coded output. |

---

# Permissions

In linux permissions are called **modes**.

## Understanding File Types

The `ls -l` command displays long listings of files and directories, including the file types.

```bash
sri@envy:~/Documents/Linux
$ ls -l
total 3248
-rw-rw-r-- 1 sri sri 236154 Jan 3 05:21 README.md
^
^
```
The first character of the permission string indicates the file type. Here are the common file types:

| **Symbol** | **File Type** | **Example** |
|------------|---------------|-------------|
| `-`| Regular file| `-rw-r--r-- 1 sri users 10400 Jun 14 09:31 sales.data`|
| `b`| Block special file | `brw-rw---- 1 root disk 8, 0 Jan 1 00:00 sda`|
| `c`| Character special file | `crw-rw-rw- 1 root tty 4, 1 Jan 1 00:00 tty1`|
| `d`| Directory| `drwxr-xr-x 2 sri users 4096 Jun 14 09:31 documents`|
| `l`| Symbolic link| `lrwxrwxrwx 1 sri users 11 Jun 14 09:31 mylink -> /etc/hosts`|
| `p`| FIFO (named pipe)| `prw-r--r-- 1 sri users 0 Jun 14 09:31 mypipe`|
| `s`| Socket| `srw-rw-rw- 1 sri users 0 Jun 14 09:31 mysocket`|
| `?`| Unknown file type| `?-????????? ? ? ? ? ? unknownfile`|

The remaining characters in the permission string represent three main types of permissions.

## Types of Permissions

Permissions are represented by three symbols: **read (`r`)**, **write (`w`)**, and **execute (`x`)**. Each permission grants specific abilities over files and directories.

| **Symbol** | **Permission** |
|------------|----------------|
| `r` | Read |
| `w` | Write |
| `x` | Execute |

### Permission Types for Directories

For files, the meanings of these permissions are straightforward:
- **Read** (`r`): Allows viewing the file's contents.
- **Write** (`w`): Allows modifying the file.
- **Execute** (`x`): Allows running the file as a program.

### Permission Types for Directories

For directories, the meanings differ slightly:
- **Read** (`r`): Allows viewing the names of files in the directory.
- **Write** (`w`): Allows modifying the directory's contents (creating, renaming, or deleting files).
- **Execute** (`x`): Allows entering the directory (`cd` command).

```bash
sri@envy:~
$ ls -ld /home/sri/Documents/
drwxr-xr-x 13 sri sri 4096 Jan 1 13:35 /home/sri/Documents/
```

In this case:
- `drwxr-xr-x`: Indicates a directory (`d` at the beginning).
- The permissions `rwxr-xr-x` mean that the owner (`sri`) can read, write, and execute; the group (`sri`) can read and execute, but not write; others can also read and execute but cannot write.

> **Note** the permission `r` for a directory allows an entity to view the entries of the directory, but to read the content of items present in the directory, they need appropriate file permissions.

## User Categories for Permissions

All files in Linux are owned by a user and a group. This allows for unique permissions to be applied for three sets of users for managing file ownership and permissions:
1. **User** (`u`): The file owner.
2. **Group** (`g`): The group associated with the file.
3. **Other** (`o`): All other users.
4. **All** (`a`): Refers to all three categories (`u`, `g`, and `o`).

When modifying file permissions, these categories are referenced to define who gets which permission.

| **Symbol** | **Category** |
|------------|--------------|
| `u`| User |
| `g`| Group|
| `o`| Other|
| `a`| All |

For example,
```bash
$ ls -l sales.data
-rw-r--r-- 1 sri users 10400 Jun 14 09:31 sales.data
```

Here:
- **User** (`sri`) is the file owner.
- **Group** (`users`) is the group owner.
- **Others** are anyone else who is not the owner or part of the group.

### Group
Every user is a member of at least one group, called their primary group. However, users can be members of many groups. Groups bring in user organization, eg. group called "sales" can contain all the employees from sales department.

To see which groups you belong to, you can run the following commands:

```bash
# Syntax
$ groups

# Example
sri@envy:~
$ groups
sri adm cdrom sudo dip plugdev users lpadmin
sri@envy:~
$

# Syntax
$ id
$ id -G
$ id -Gn

# Examples
sri@envy:~
$ id
uid=1000(sri) gid=1000(sri) groups=1000(sri),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),100(users),114(lpadmin)
sri@envy:~
$ id -G
1000 4 24 27 30 46 100 114
sri@envy:~
$ id -Gn
sri adm cdrom sudo dip plugdev users lpadmin
sri@envy:~
$
```

For another user:

```bash
# Syntax
$ groups [username]

# Example
sri@envy:~/Documents/Linux
$ groups root
root : root
sri@envy:~/Documents/Linux
$ groups sri
sri : sri adm cdrom sudo dip plugdev users lpadmin
sri@envy:~/Documents/Linux
$
```

These commands display the groups the user belongs to, which help in determining the permissions granted to each user category.

## Decoding Permissions

Linux file permissions are displayed using a **10-character string**, which can be decoded as follows:

1. **File Type** (1st Character):
- Indicates the type of file.
- `-` = Regular file
- `d` = Directory
- `l` = Symbolic link

1. **Permissions** (Next 9 Characters):
- Split into **user (owner)**, **group**, and **others**.
- Each group has **read (r)**, **write (w)**, and **execute (x)** permissions.
- If a permission is missing, it's represented by `-`.

1. **Trailing Characters in Permission Strings**
* Sometimes, additional characters indicate special access control methods:
- **`.` (Trailing Period)**: Indicates an SELinux security context.
- **`+` (Trailing Plus)**: Indicates Access Control Lists (ACLs).

```bash
$ ls -l sales.data
-rw-r--r-- 1 sri users 10400 Jun 14 09:31 sales.data
```
- File type: `-` (regular file)
- User (owner): `rw-` (read and write)
- Group: `r--` (read-only)
- Others: `r--` (read-only)
- Owner: `sri`
- Group: `users`

```bash
$ ls -l sales.data.selinux
-rw-r--r--. 1 sri users 1040 Jun 14 09:31 sales.data.selinux
# SELinux context applied.

$ ls -l sales.data.acl
-rw-r--r--+ 1 sri users 1040 Jun 14 09:31 sales.data.acl
# ACLs are in use.
```

**Tips for Troubleshooting:**
- If you notice a trailing character (`.` or `+`), additional investigation may be required, as these security mechanisms can affect file access.

## Changing Permissions

Linux provides the `chmod` (**change mode**) command to modify file permissions. Permissions can be changed either using **symbolic** or **numeric (octal) modes**.

### 1. Symbolic Mode Permissions

In **symbolic mode**, you can modify file or directory permissions in a human-readable format. The symbolic notation allows you to specify **who** the change applies to, **what action** to perform, and **which permissions** to apply or remove.

```bash
# Syntax
$ chmod [user][operation][permissions] [file]
```

#### Components
1. **[user]:** Specifies which set of users the change applies to:
- `u`: The owner of the file (user).
- `g`: The group associated with the file.
- `o`: All other users (others).
- `a`: All users (shorthand for `u`, `g`, and `o`).

2. **[operation]:** Defines what action to take:
- `+`: Add the specified permissions if not already present.
- `-`: Remove the specified permissions if not already present.
- `=`: Set the permissions **exactly** as specified, overriding existing ones.

3. **[permissions]:** The type of access being granted or removed:
- `r`: Read permission (view file contents).
- `w`: Write permission (modify file contents).
- `x`: Execute permission (run the file as a program/script).

---

#### Examples

##### 1. Add execute permission for the user (owner):
```bash
# Syntax
$ chmod u+x myscript.sh

# Example
sri@envy:~/Desktop
$ ls afile.txt -l
-rw-rw-r-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod u+x afile.txt
sri@envy:~/Desktop
$ ls -l afile.txt
-rwxrw-r-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- Adds execute (`x`) permission for the file's owner (`u`).
- After this, the owner can run the script as a program.

##### 2. Remove write permission for the group:
```bash
# Syntax
$ chmod g-w myscript.sh

# Example
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrwxr-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod g-x afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrw-r-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$

```
- Removes write (`w`) permission for the file's group (`g`).
- Members of the group can no longer modify the file.

##### 3. Set read-only permission for others:
```bash
# Syntax
$ chmod o=r file.txt

# Example
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrw-rwx 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod o=r afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrw-r-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- Sets the permission for others (`o`) to read-only (`r`).
- Removes any existing write or execute permissions for others.

##### 4. Allow all users to execute a file:
```bash
# Syntax
$ chmod a+x program.sh

# Example
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod a+x afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---x--x--x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- Adds execute permission for all users (`a`), including owner, group, and others.

##### 5. Set exact permissions for the group:
```bash
# Syntax
$ chmod g=rw myfile.txt

# Example
sri@envy:~/Desktop
$ ls -l
total 0
---x--x--x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod g=rw afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---xrw---x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- Sets the group (`g`) permissions to read (`r`) and write (`w`) only.
- Removes any execute or other permissions previously set for the group.

##### 6. Remove all permissions for others:
```bash
# Syntax
$ chmod o= mydoc.txt

# Example
sri@envy:~/Desktop
$ ls -l
total 0
---xrw---x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod o= afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---xrw---- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- Removes all permissions for others (`o`), making the file inaccessible to them.
- Simiarly you can remove all the permission for others as well using `a=`.

##### 7. Multiple Changes in One Command:
You can modify permissions for different categories simultaneously. For example:
```bash
# Sytnax
$ chmod u+x,g-w,o=r file.txt

# Example
sri@envy:~/Desktop
$ chmod a= afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod a+x,g+r,u+rw afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rwxr-x--x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```

##### 8. Explicit Permission Setting:
The equal sign (`=`) can be used to overwrite existing permissions for a user category:
```bash
# Syntax
$ chmod u=rwx file.txt

# Example
sri@envy:~/Desktop
$ chmod u=wx afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
--wxr-x--x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$

```
This sets the user's permissions to read, write, and execute, overriding any existing permissions for the user category.

---

### 2. Numeric Mode Permissions

In **numeric (octal) mode**, file permissions are represented using a three-digit number, where each digit specifies the permissions for a different category of users: **owner (user)**, **group**, and **others**. Each digit is the sum of the numeric values assigned to the permissions:

- `r` (read) = **4**
- `w` (write) = **2**
- `x` (execute) = **1**
- No permission = **0**

By adding these values together, you can represent any combination of permissions numerically.

---

#### Permissions Table

The following table shows how the numeric values correspond to permission combinations:

| **Permissions** | **Numeric Value** | **Description** |
|------------------|-------------------|-------------------------------------|
| `rwx`| 7 | Read, write, and execute|
| `rw-`| 6 | Read and write |
| `r-x`| 5 | Read and execute|
| `r--`| 4 | Read only |
| `-wx`| 3 | Write and execute |
| `-w-`| 2 | Write only |
| `--x`| 1 | Execute only|
| `---`| 0 | No permissions |

---

#### How It Works

For example, `chmod 754` assigns:
- **7** (rwx): Owner has full permissions (read, write, execute).
- **5** (r-x): Group can read and execute, but not write.
- **4** (r--): Others can only read.

1. **Structure of Permissions**:
- The **first digit** applies to the file **owner**.
- The **second digit** applies to the **group**.
- The **third digit** applies to **others** (everyone else).

2. **Calculating the Numeric Value**:
- Add the numeric values for the desired permissions.
- Example: `rw-` (read + write) = `4 + 2 = 6`.

The below method of specification also works:
```bash
sri@envy:~/Desktop
$ chmod 7 dir
sri@envy:~/Desktop
$ ls -ld dir
d------rwx 2 sri sri 4096 Jan 3 10:58 dir

sri@envy:~/Desktop
$ chmod 77 dir
sri@envy:~/Desktop
$ ls -ld dir
d---rwxrwx 2 sri sri 4096 Jan 3 10:58 dir

sri@envy:~/Desktop
$ chmod 777 dir
sri@envy:~/Desktop
$ ls -ld dir
drwxrwxrwx 2 sri sri 4096 Jan 3 10:58 dir

sri@envy:~/Desktop
$
```

---

#### Examples of chmod in Numeric Mode

##### 0. Remove all permissions (lock a file):
```bash
$ chmod 000 secretfile.txt
```
- **0** (---): Owner, group, and others have no access.

##### 1. Give the owner full permissions, and the group and others read-only:
```bash
# Syntax
$ chmod 744 myfile.txt

# Example
sri@envy:~/Desktop
$ chmod 000 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod 774 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrwxr-- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$

```
- **7** (rwx): Owner can read, write, and execute.
- **4** (r--): Group can only read.
- **4** (r--): Others can only read.

##### 2. Give the owner read and write permissions, and no permissions to the group and others:
```bash
# Syntax
$ chmod 600 myfile.txt

# Example
sri@envy:~/Desktop
$ chmod 000 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod 600 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rw------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$

```
- **6** (rw-): Owner can read and write.
- **0** (---): Group has no permissions.
- **0** (---): Others have no permissions.

##### 3. Give everyone execute permission only:
```bash
# Syntax
$ chmod 111 script.sh

# Example
sri@envy:~/Desktop
$ chmod 000 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod 111 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---x--x--x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$

```
- **1** (--x): Owner can only execute.
- **1** (--x): Group can only execute.
- **1** (--x): Others can only execute.

##### 4. Set permissions for a shared script:
```bash
# Syntax
$ chmod 775 shared_script.sh

# Example
sri@envy:~/Desktop
$ chmod 000 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod 775 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rwxrwxr-x 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- **7** (rwx): Owner can read, write, and execute.
- **7** (rwx): Group can read, write, and execute.
- **5** (r-x): Others can read and execute, but not write.

##### 5. Make a file readable and writable by everyone:
```bash
# Syntax
$ chmod 666 openfile.txt

# Example
sri@envy:~/Desktop
$ chmod 000 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
---------- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$ chmod 666 afile.txt
sri@envy:~/Desktop
$ ls -l
total 0
-rw-rw-rw- 1 sri sri 0 Jan 3 05:43 afile.txt
sri@envy:~/Desktop
$
```
- **6** (rw-): Owner can read and write.
- **6** (rw-): Group can read and write.
- **6** (rw-): Others can read and write.

#### Key Benefits of Numeric Mode
- **Precision**: Numeric mode explicitly defines all permissions at once.
- **Efficiency**: A single command can adjust permissions for all user categories.
- **Control**: You can quickly lock or open a file for specific users.

---

#### Common Octal Permissions

Here are some commonly used permission sets and their symbolic, binary, and octal representations:

| **Symbolic** | **Octal** | **Meaning** |
|----------------|-----------|------------------------------------------------------------------------------------------------------|
| `-rwx------` | `700` | Owner has full control over the file; no one else has access. For confidential file|
| `-rwxr-xr-x` | `755` | Owner has full control; everyone else can execute the file but only the owner can edit it.|
| `-rw-rw-r--` | `664` | Owner and group members can modify the file; others can only read it.|
| `-rw-rw----` | `660` | Owner and group members can modify the file; others have no access. |
| `-rw-r--r--` | `644` | Owner can modify the file; everyone else can only read it. For public document|

### Understanding Security Risks with Permissions

It's crucial to avoid overly permissive permissions, such as `777` and `666`. These allow anyone on the system to read, write, or execute the file, which poses significant security risks. Some of the potential issues include:

- **Accidental Changes**: If a file has `777` permissions, anyone on the system can modify it, which could lead to accidental changes.
- **Privilege Escalation**: Malicious users could modify a script or program, introduce harmful code, and cause it to execute when someone else runs the file.
- **Data Destruction**: With `777` or `666` permissions, malicious or careless users can delete or corrupt important data.

### Best Practice:
* Use appropriate permissions for different users and groups.
* Limit access to sensitive files and make use of groups to provide controlled access.
* Avoid using `777` or `666` permissions unless absolutely necessary. For example, if multiple users need write access, use groups and restrict permissions for others.

## Working with Groups

When multiple users need access to the same file, Linux group ownership and permissions are useful tools for managing file access.

#### To view existing Groups
```bash
# Syntax
$ cat /etc/group

# Example
sri@envy:~/Desktop
$ cat /etc/group
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:syslog,sri
tty:x:5:
disk:x:6:
```
The output shows the contents of the `/etc/group` file, which defines the groups on a Linux system. Each line represents a group and follows this format:

```bash
GROUP_NAME:PASSWORD:GID:MEMBERS
```

- **GROUP_NAME**: The name of the group.
- **PASSWORD**: Typically `x`, indicating that group passwords are stored in a shadow file (not commonly used anymore).
- **GID**: The Group ID, a unique numeric identifier for the group.
- **MEMBERS**: A comma-separated list of users who belong to the group.

---

#### Creating a Group
```bash
# Syntax
$ groupadd [options] GROUP_NAME

# Example
sri@envy:~/Desktop
$ groupadd a_new_group
groupadd: Permission denied.
groupadd: cannot lock /etc/group; try again later.
sri@envy:~/Desktop
$ sudo groupadd a_new_group
[sudo] password for sri:
sri@envy:~/Desktop
$ cat /etc/group | grep a_new_
a_new_group:x:1001:
sri@envy:~/Desktop
$
```

---

### Adding Users to the Group

To add a user (e.g., `sri`) to the group:
```bash
# Syntax
$ sudo usermod -aG group userid

# Example
sri@envy:~/Desktop
$ sudo usermod -aG a_new_group sri
sri@envy:~/Desktop
$ groups sri | grep a_new
sri : sri adm cdrom sudo dip plugdev users lpadmin a_new_group
sri@envy:~/Desktop
$
```
---

### Creating a Group with a Specific GID
If you want to assign a specific Group ID (GID) to the group:
```bash
# Syntax
$ sudo groupadd -g

# Example
sri@envy:~/Desktop
$ sudo groupadd another_new_group -g 2000
sri@envy:~/Desktop
$ cat /etc/group | grep another
another_new_group:x:2000:
sri@envy:~/Desktop
$
```

---

### Deleting a Group
If you need to delete a group:
```bash
# Syntax
$ sudo groupdel

# Examples
sri@envy:~/Desktop
$ sudo groupdel another_new_group
sri@envy:~/Desktop
$ sudo groupdel a_new_group
sri@envy:~/Desktop
$
```

---

### Summary of group related commands

| **Command** | **Description** |
|---------------------------|----------------------------------------------|
| `sudo groupadd GROUP_NAME`| Create a group |
| `cat /etc/group` | List all groups |
| `sudo usermod -aG GROUP_NAME USER_NAME` | Add a user to a group |
| `groups USER_NAME`| Check user groups|
| `sudo groupdel GROUP_NAME`| Delete a group |

---

### Changing Group Ownership

Use the `chgrp` command to change the group owner of a file.

**Example:**
First let's create a group called `sales`.
```bash
sri@envy:~/Desktop
$ sudo groupadd sales
sri@envy:~/Desktop
$ cat /etc/group | grep sal
sales:x:1001:
sri@envy:~/Desktop
$
```
Create a file, `sales.report`, with default group ownership:
```bash
sri@envy:~/Desktop
$ touch sales.report
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw-r-- 1 sri sri 0 Jan 3 06:53 sales.report
sri@envy:~/Desktop
$
```
- Default group: `sri` (sri's primary group).

Change group ownership to `sales`:
```bash
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw-r-- 1 sri sri 0 Jan 3 06:53 sales.report
sri@envy:~/Desktop
$ chgrp sales sales.report
chgrp: changing group of 'sales.report': Operation not permitted
sri@envy:~/Desktop
$ sudo chgrp sales sales.report
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw-r-- 1 sri sales 0 Jan 3 06:53 sales.report
sri@envy:~/Desktop
$
```
- New group: `sales`.

---

#### Setting Permissions for Group Access

- Use `chmod` to grant appropriate permissions to the group.
- Recommended permissions for non-executable files:
- `664 (rw-rw-r--)`: User and group can read/write; others can read. This is also the default option in Ubuntu 24.04.
- `660 (rw-rw----)`: User and group can read/write; no access for others.

**Example:**
Set group read/write permissions (660):
```bash
sri@envy:~/Desktop
$ chmod 660 sales.report
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw---- 1 sri sales 0 Jan 3 06:53 sales.report
sri@envy:~/Desktop
$

```
- Group members (`sales`) can now read and modify the file.

**Deleting a group**
```bash
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw---- 1 sri sales 0 Jan 3 06:53 sales.report
sri@envy:~/Desktop
$ sudo groupdel sales
sri@envy:~/Desktop
$ ls -l sales.report
-rw-rw---- 1 sri 1001 0 Jan 3 06:53 sales.report
^^^^
sri@envy:~/Desktop
$
```

---

#### Sharing Files in a Common Directory

- **Shared Location**: It's more convenient to use a common directory for group files, such as `/usr/local/sales`.
- The directory group owner should be set to the relevant group (e.g., `sales`).
- Recommended directory permissions:
- `775 (rwxrwxr-x)`: User and group have full access; others can read/execute.
- `770 (rwxrwx---)`: Only user and group have full access.

**Example:**
Create a shared directory:
```bash
$ ls -ld /usr/local/sales
drwxrwxr-x 2 root sales 4096 Jun 15 20:53 /usr/local/sales
```
- Group owner: `sales`.
- Permissions: `775`.

Move the file to the shared directory:
```bash
$ mv sales.report /usr/local/sales/
$ ls -l /usr/local/sales
total 4
-rw-rw-r-- 1 sri sales 6 Jun 15 20:41 sales.report
```
- `sales.report` is now accessible to all group members.

---

### Key Points
- Use `chgrp` to assign a file to a group.
- Adjust file permissions (`chmod`) to control group access.
- Shared directories simplify collaboration and should have appropriate group ownership and permissions.

## Directory Permissions

Directory permissions are critical in controlling access to files and subdirectories within the directory. While file permissions dictate how a file can be read, written, or executed, directory permissions determine how the files and subdirectories inside it are accessed, listed, or modified.

### Understanding Directory Permissions

The permissions for directories are interpreted differently compared to regular files. Here's what each permission means for a directory:

| **Permission** | **Effect on Directory** |
|----------------|-------------------------|
| `r` (read) | Allows viewing the names of the files and subdirectories inside the directory (e.g., `ls` command). |
| `w` (write)| Allows creating, deleting, or renaming files and subdirectories within the directory.|
| `x` (execute) | Allows entering the directory (e.g., `cd` command) and accessing files or subdirectories if permissions allow. |

Directory permission usually only contain **0s**, **5s**, and **7s**. Common directory permissions include **755**, **700**, **770**, and **750**.

---

### Permission Combinations for Directories