# 2.4 Creating, Moving and Deleting Files

### **2.4 Creating, Moving and Deleting Files**

**Weight:** 2

**Description:** Create, move and delete files and directories under the home directory.

**Key Knowledge Areas:**

* Files and directories
* Case sensitivity
* Simple globbing

**The following is a partial list of the used files, terms and utilities:**

* mv, cp, rm, touch
* mkdir, rmdir

## File Management in Linux

File management in Linux involves handling files and directories through various operations such as creation, modification, organization, and access control within the filesystem.

* Linux treats everything as a file, including devices and system configurations.
* Ensures efficient data organization and accessibility.
* Involves operations like create, copy, move, rename, and delete.
* Uses file permissions and ownership for secure access control.
* Common commands include cp, mv, rm, ls, cat, and chmod.
*

Linux categorizes files into three main types, each serving a specific purpose in the system:

<figure><img src="/files/J3jZLHBUZUFrQpfRTGVc" alt=""><figcaption></figcaption></figure>

#### **1. General Files** <a href="#id-1-gereral-files" id="id-1-gereral-files"></a>

These are the most common file types that store user data such as text files, images, and binaries.

* Represent regular data like documents, programs, or scripts.
* Can be created using the `touch` command.
* Form the majority of files in Linux/UNIX systems.
* May contain human-readable text (ASCII), executable binaries, or program data.

#### **2. Directories:** <a href="#id-2-directories" id="id-2-directories"></a>

These act as containers that organize files and other directories hierarchically.

* Similar to folders in Windows.
* Store lists of file names and their related metadata.
* New directories can be created using the `mkdir` command.

Important directories include:

* **`/:`** Root directory (base of the system)
* **`/home/:`**&#x55;ser home directories
* **`/bin/:`** Essential user binaries
* **`/boot/:`** Static boot files

#### **3. Device Files:** <a href="#device-files" id="device-files"></a>

These files represent hardware devices and handle input/output (I/O) operations.

* Used to interact with physical devices like printers, disks, or terminals.
* Found mostly in the `/dev/` directory.
* Allow the operating system to treat hardware as if it were a regular file.

### **Listing Files**

#### **ls**

To list files and directories in Linux, the **`ls`** command is used. It provides a quick view of the contents of a directory, including files, subdirectories, and optional details like permissions, ownership, and timestamps.

```
[payam@earth boot]$ ls
config-5.14.0-427.13.1.el9_4.x86_64                      initramfs-5.14.0-570.58.1.el9_6.x86_64.img       System.map-5.14.0-427.13.1.el9_4.x86_64
config-5.14.0-570.58.1.el9_6.x86_64                      initramfs-5.14.0-570.58.1.el9_6.x86_64kdump.img  System.map-5.14.0-570.58.1.el9_6.x86_64
config-5.14.0-611.9.1.el9_7.x86_64                       initramfs-5.14.0-611.9.1.el9_7.x86_64.img        System.map-5.14.0-611.9.1.el9_7.x86_64
efi                                                      loader                                           vmlinuz-0-rescue-22436a1199ae4759988a41bf856d1985
grub2                                                    symvers-5.14.0-427.13.1.el9_4.x86_64.gz          vmlinuz-5.14.0-427.13.1.el9_4.x86_64
initramfs-0-rescue-22436a1199ae4759988a41bf856d1985.img  symvers-5.14.0-570.58.1.el9_6.x86_64.gz          vmlinuz-5.14.0-570.58.1.el9_6.x86_64
initramfs-5.14.0-427.13.1.el9_4.x86_64.img               symvers-5.14.0-611.9.1.el9_7.x86_64.gz           vmlinuz-5.14.0-611.9.1.el9_7.x86_64

```

* Lists all files and directories in the current directory.
* Each type of file is displayed with a different color for easy identification.
* Directories are typically shown in dark blue.
* Helps visually distinguish between files, directories, and other file types.
* Makes navigating and understanding directory contents faster and more intuitive.

Running **`ls -l`** returns a **detailed listing** of files and directories in the current directory.

```
[payam@earth boot]$ ls
config-5.14.0-427.13.1.el9_4.x86_64                      initramfs-5.14.0-570.58.1.el9_6.x86_64.img       System.map-5.14.0-427.13.1.el9_4.x86_64
config-5.14.0-570.58.1.el9_6.x86_64                      initramfs-5.14.0-570.58.1.el9_6.x86_64kdump.img  System.map-5.14.0-570.58.1.el9_6.x86_64
config-5.14.0-611.9.1.el9_7.x86_64                       initramfs-5.14.0-611.9.1.el9_7.x86_64.img        System.map-5.14.0-611.9.1.el9_7.x86_64
efi                                                      loader                                           vmlinuz-0-rescue-22436a1199ae4759988a41bf856d1985
grub2                                                    symvers-5.14.0-427.13.1.el9_4.x86_64.gz          vmlinuz-5.14.0-427.13.1.el9_4.x86_64
initramfs-0-rescue-22436a1199ae4759988a41bf856d1985.img  symvers-5.14.0-570.58.1.el9_6.x86_64.gz          vmlinuz-5.14.0-570.58.1.el9_6.x86_64
initramfs-5.14.0-427.13.1.el9_4.x86_64.img               symvers-5.14.0-611.9.1.el9_7.x86_64.gz           vmlinuz-5.14.0-611.9.1.el9_7.x86_64

```

Displays important information such as:

* File permissions (who can read, write, or execute)
* Owner and group of each file
* File size and last modification date
* Helps determine which users or groups can access or manage each file, providing insights into system security and file management.

{% hint style="success" %}

### Wildcards and Globbing <a href="#wildcards-and-globbing" id="wildcards-and-globbing"></a>

\
**File globbing is a feature provided by the UNIX/Linux shell to represent multiple filenames by using special characters called wildcards with a single file name.** A wildcard is essentially a symbol which may be used to substitute for one or more characters. Therefore, we can use wildcards for generating the appropriate combination of file names as per our requirement.

**Question mark – (?)  is used to match any single character.  example:**  `ls -l ????.txt`

**Asterisk – (\*)  is used to match zero or more characters. example:** `ls -l *.pl`

**Square Brackets \[]**  **is used to match the character from the range.. example:**  `ls -l [p-s]*`
{% endhint %}

### **Creating Files** <a href="#id-2-creating-files" id="id-2-creating-files"></a>

#### **touch**

* The `touch` command is used to create a new file in Linux.
* If the specified file does not exist, `touch` creates a new blank file.
* If the file already exists, its contents remain unaffected, and only the file’s timestamp may be updated.
* This command is a quick and simple way to create empty files for various purposes.

```
[payam@earth ~]$ touch file1
[payam@earth ~]$ ls
Desktop  Documents  Downloads  file1  kubeconf  Music  Pictures  Public  Templates  Videos
```

### **Moving a File** <a href="#id-5-moving-a-file" id="id-5-moving-a-file"></a>

#### **mv**

* The **`mv`** command is used to **move a file** from one location to another in Linux.
* It **removes the file** from the source directory and **creates it** in the destination directory with the **same name and content**.
* This command can also be used to **rename files** by specifying a different name at the destination.

```
mv source/filename destination/
```

### **Renaming a File** <a href="#id-6-renaming-a-file" id="id-6-renaming-a-file"></a>

* The `mv` command can also be used to rename a file in Linux.
* It changes the file name from `filename` to `new_filename` while retaining the file’s content.
* Essentially, the original file is replaced with a file of the new name without altering the data.

```
mv filename new_filename
```

### **Deleting a File** <a href="#id-7-deleting-a-file" id="id-7-deleting-a-file"></a>

#### **rm**

* The `rm` command is used to delete a file in Linux.
* It permanently removes the specified file from the directory.
* Use this command carefully, as deleted files cannot be easily recovered.

```
rm filename
```

{% hint style="danger" %}
You can not restore files. use with caution.
{% endhint %}

***

## &#x20;Directory management in Linux?

\
As we said, **directories** in Linux are special types of files that store references (paths) to other files and directories, organizing the filesystem in a hierarchical structure.

* Directories act as containers for files and subdirectories.
* The root directory (`/`) is the top-level directory in Linux.
* Special directories like `.` (current directory) and `..` (parent directory) are used for navigation.
* Each directory can contain multiple files and subdirectories.

## Creating Directories <a href="#id-1-creating-directories" id="id-1-creating-directories"></a>

#### mkdir

To create a directory in Linux you have to use mkdir command which stands for make directory.

```
mkdir directory_name
```

example:

```
[payam@earth ~]$ mkdir mydir1
```

#### Listing Directories <a href="#id-2-listing-directories" id="id-2-listing-directories"></a>

To list directories, you can use the `ls` command. Adding the `-l` flag provides detailed information about each item, including whether it’s a file or directory. In the detailed output, entries that start with a **‘d’** (e.g., `drwxrwxr-x`) indicate directories.

```
[payam@earth ~]$ ls -lrth
total 12K
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Videos
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Templates
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Public
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Music
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Documents
drwxr-xr-x. 2 payam payam    6 Nov 17 12:09 Desktop
drwx------. 3 payam payam 4.0K Nov 18 15:29 kubeconf
drwxr-xr-x. 2 payam payam 4.0K Nov 30 14:31 Pictures
drwxr-xr-x. 4 payam payam 4.0K Dec  2 10:59 Downloads
-rw-r--r--. 1 payam payam    0 Dec  2 11:27 file1
drwxr-xr-x. 2 payam payam    6 Dec  2 11:39 mydir1
```

You can also list a directory's content by using ls command

```
ls path/to/directory
```

### Removing Directories <a href="#id-3-removing-directories" id="id-3-removing-directories"></a>

#### rmdir

To remove a directory you can use  **`rmdir`**  but for that the directory must be empty

```
rmdir directory_name 
```

To remove a directory which has contents in it use '**rm'** with recursive flags '**-r**' or '**-rf**'

```
rm -rf directory_name
```

{% hint style="danger" %}
This will delete the directory with all its content inside it.
{% endhint %}

#### Changing Directories <a href="#id-4-changing-directories" id="id-4-changing-directories"></a>

To change directories you have  `cd`  with various attributes.

```
cd Directory_name
```

If directory is somewhere else then give the path also with directory name.

```
cd /path/to/directory/ Some code
```

To move back to last directory you were in

```
cd -
```

To move to the parent directory of your current directory use

```
cd ..
```

* To move back to the default directory use (home)

```
cd ~
```

To check in current directory use (while it has no much use case other than scripting but it is still useful to know it)

```
cd .
```

### Copying Directories <a href="#id-5-copying-directories" id="id-5-copying-directories"></a>

* To copy a directory, use the `cp` command with the **`-r` (recursive)** flag to ensure all contents inside the directory are copied as well.
* You can copy a directory from any location by providing the **full path** of both the source and destination.
* This command works even if you’re **not in the parent directory** of the directory being copied.
* Make sure you have the **required permissions** to access and copy the directory.

```
cp -r source_dir destination_dir
```

### Moving or Renaming Directories <a href="#id-6-moving-or-renaming-directories" id="id-6-moving-or-renaming-directories"></a>

* To move or rename a directory, for both '**mv'** command is used.
* To move a directory provide the path of source directory and destination path. You can move a directory from and to anywhere, you just need to provide correct path with directory name which you want to move and the destination where you want to move, required you have permission to do so.

```
mv source_dir /path/to/destination
```

To rename a directory you need to present in the parent directory. just provide the old name and followed by new name.

```
mv old_name new_name
```

### Checking Directories Size

#### du<br>

To check a directories/files size use `du` command and to get in human readable format (kb,mb,gb) use `-h`  with it.

```
du -h
```

```
[root@earth boot]# du -h
1.1M	./efi/EFI/BOOT
6.1M	./efi/EFI/rocky
17M	./efi/EFI/Lenovo/BIOS
17M	./efi/EFI/Lenovo
24M	./efi/EFI
2.0K	./efi/System Volume Information
24M	./efi
2.3M	./grub2/fonts
2.3M	./grub2
20K	./loader/entries
20K	./loader
516M	.

```

***

### Case Sensitivity in Linux

Case sensitivity in Linux refers to files and directories recognizing differences between lowercase and uppercase characters in filenames. For instance, "File.txt" and "file.txt" would both be treated as two distinct files. This concept is integral to Unix-like operating systems, including Linux.

Linux offers numerous benefits from choosing this design option in file naming: it reduces ambiguity in file names, prevents accidental overwrites, and can increase performance because no case normalization checks need to be performed for every file access. From a security perspective, these features also mitigate attacks that involve character case manipulation to bypass security controls.

***

## globbing

In Linux, a glob is a pattern-matching mechanism used for filename expansion in the shell. The term "glob" represents the concept of matching patterns globally or expansively across multiple filenames or paths. It allows users to specify wildcard patterns to match files or directories based on certain criteria. The globbing feature in Linux provides flexibility and efficiency when working with multiple files.

By using wildcards like an asterisk **(\*)** or question mark **(?)**, users can match filenames or paths that meet specific patterns, simplifying tasks such as listing, copying, moving, or deleting files. Globbing is an integral part of the Linux shell, making it easier to perform operations on groups of files by expanding the specified pattern into a list of matching filenames.

### Wildcard Matching <a href="#wildcard-matching" id="wildcard-matching"></a>

Glob Linux supports several wildcard characters for pattern matching.&#x20;

#### Asterisk (\*) <a href="#asterisk" id="asterisk"></a>

The asterisk (\*) is a powerful wildcard character in glob Linux that matches any number of characters (including none) within a filename or path segment. It is used for pattern matching.

For example, \*.txt matches all files with a .txt extension in the current directory.

```
ls *.txt
```

#### Question Mark (?) <a href="#question-mark" id="question-mark"></a>

The question mark (?) in glob Linux is a wildcard character matching any single character within a filename or path segment. It is useful for matching files with a specific pattern.

For example, file?.txt matches files like file1.txt or fileA.txt, but not file10.txt.

```
ls file?.txt
```

There are more and more way of using globbing byt that 's enough for know.

.

.

.

***

sources:

<https://www.geeksforgeeks.org/linux-unix/file-management-in-linux/>\
<https://www.geeksforgeeks.org/linux-unix/how-to-manage-directories-in-linux/>\
<https://linuxsecurity.com/features/linux-filesystem-case-sensitivity-debate#:~:text=Case%20sensitivity%20in%20Linux%20refers,treated%20as%20two%20distinct%20files.>\
<https://www.scaler.com/topics/glob-linux/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://borosan.gitbook.io/lpi-linux-essentials/2.4-creating-moving-and-deleting-files.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
