Manage Files and Directories in Linux

CompTIABeginner
Practice Now

Introduction

In this lab, you will learn the fundamental skills for managing files and directories within a Linux command-line environment. You will gain hands-on experience creating and removing complex directory structures using mkdir and rm, as well as copying and moving files and directories with cp and mv.

Furthermore, this lab provides a detailed exploration of file linking. You will create both symbolic (soft) and hard links using the ln command, analyze the underlying concept of inodes, and observe the distinct behaviors of each link type when the source file is modified. This will provide a deeper understanding of how the Linux file system organizes and references data.

Create and Remove Directory Structures with mkdir, rmdir, and rm

In this step, you will learn how to create and remove directories. Organizing files into a hierarchical structure of directories is a fundamental task in Linux. We will use the mkdir command to create directories, rmdir to remove empty directories, and rm to remove directories and all of their contents. All commands will be executed from your default directory, ~/project.

First, let's create a simple directory. The mkdir command stands for "make directory".

In your terminal, execute the following command to create a directory named cars:

mkdir cars

To verify that the directory has been created, you can use the ls -ld command. The -l option provides a long listing format, and the -d option lists the directory entry itself, not its contents.

ls -ld cars

You should see output similar to this, confirming the creation of the cars directory. The d at the beginning of the permissions string indicates that it is a directory.

drwxr-xr-x 2 labex labex 4096 May 20 10:30 cars

Now, let's remove this directory. The rmdir command is used to remove empty directories.

rmdir cars

Verify its removal by running the ls -ld command again.

ls -ld cars

This time, you will receive an error message because the directory no longer exists. This confirms that rmdir was successful.

ls: cannot access 'cars': No such file or directory

The rmdir command only works on empty directories. What if we have a structure of nested directories? Let's try to create a directory structure pastry/pies/cakes. To create parent directories as needed, we must use the -p (parents) option with mkdir.

Execute the following command:

mkdir -p pastry/pies/cakes

To view the entire directory structure you just created, use the ls command with the -l (long format) and -R (recursive) options.

ls -lR pastry

The output will show the pastry directory and its subdirectories, pies and cakes.

pastry:
total 4
drwxr-xr-x 3 labex labex 4096 May 20 10:35 pies

pastry/pies:
total 4
drwxr-xr-x 2 labex labex 4096 May 20 10:35 cakes

pastry/pies/cakes:
total 0

Now, let's try to remove the pastry directory using rmdir.

rmdir pastry

Why did this command fail? The terminal will show an error message:

rmdir: failed to remove 'pastry': Directory not empty

This is because rmdir can only delete empty directories, and pastry contains the pies subdirectory.

To remove a directory and all of its contents (including subdirectories and files), you must use the rm command with the -r (recursive) option. Be very careful with this command, as it can permanently delete data.

rm -r pastry

This command will not produce any output if successful. You can verify that the pastry directory has been completely removed by running ls -ld pastry again, which should result in a "No such file or directory" error.

ls -ld pastry

In this step, you will create a file using the vi text editor and then create a symbolic link to it. A symbolic link, also known as a symlink or soft link, is a special type of file that points to another file or directory. It's similar to a shortcut in other operating systems.

First, let's create a simple text file named filea using vi. vi is a powerful, screen-oriented text editor. It has two main modes: Command mode and Insert mode. You start in Command mode, where key presses are interpreted as commands. To type text, you must enter Insert mode.

  1. In your terminal, which should be at the ~/project path, start vi to create the file filea:
vi filea
  1. Your terminal will now display the vi editor interface. To begin typing, you need to switch to Insert mode. Press the i key once. You may see -- INSERT -- at the bottom of the screen.
  2. Now, type the following text:
This is filea.
  1. To save the file and exit vi, you must first return to Command mode by pressing the Esc key. Then, type ZZ (hold Shift and press Z twice). This command saves the file and exits the editor.

Now that you are back at the command prompt, let's verify that the file was created and contains the correct content.

First, list the file:

ls filea

The output should simply be the filename:

filea

Next, display its contents using the cat command:

cat filea

The output should match the text you entered:

This is filea.

Now, let's create a symbolic link. We will create a link named fileb that points to our original file, filea. The command is ln -s <source_file> <destination_link>.

ln -s filea fileb

To test the results, use the ls -il command. The -i option shows the inode number, which is a unique identifier for a file or directory on the filesystem.

ls -il file[ab]

Examine the output carefully.

131075 -rw-r--r-- 1 labex labex 14 May 20 10:40 filea
131076 lrwxrwxrwx 1 labex labex  5 May 20 10:41 fileb -> filea

Notice a few key things:

  • File Type: The permissions string for filea starts with a -, indicating a regular file. The string for fileb starts with an l, indicating a symbolic link.
  • Link Pointer: The output clearly shows fileb -> filea.
  • Inode Numbers: Look at the first column. The inode numbers for filea and fileb are different. Why? Because a symbolic link is a separate file that simply stores the path to the target file. It is not the file itself, so it gets its own unique inode.

Finally, let's see if we can read the content through the link.

cat fileb

The output is the content of filea:

This is filea.

This is the expected behavior. When you perform an operation like cat on a symbolic link, the system automatically follows the link to the source file and performs the operation on it.

In this step, you will create a hard link and learn how it differs from the symbolic link you created previously. Unlike a symbolic link, which is a pointer to a filename, a hard link is another name for the file itself. Both names point directly to the same data on the disk, which is identified by a unique number called an inode.

We will continue working with the files filea and fileb from the previous step in the ~/project directory.

First, let's create a hard link named filec that points to the same inode as filea. To do this, we use the ln command without the -s option.

ln filea filec

Now, let's view the contents of all three files: the original filea, the symbolic link fileb, and the new hard link filec.

cat filea
cat fileb
cat filec

You will see the same content printed three times, which is expected.

This is filea.
This is filea.
This is filea.

The real difference becomes clear when we inspect the file properties. Use the ls -il command again to view the inode numbers and other details for all three files.

ls -il file[a-c]

The output will look something like this. Pay close attention to the first and second columns.

131075 -rw-r--r-- 2 labex labex 14 May 20 10:40 filea
131076 lrwxrwxrwx 1 labex labex  5 May 20 10:41 fileb -> filea
131075 -rw-r--r-- 2 labex labex 14 May 20 10:40 filec

Let's analyze this output:

  • Inode Numbers (Column 1): Notice that filea and filec have the exact same inode number (e.g., 131075). This is the defining characteristic of a hard link. They are not separate files; they are two different names pointing to the identical file data on the disk. The symbolic link fileb has its own unique inode.
  • Link Count (Column 2): Look at the number for filea and filec. It is now 2. This number is the hard link count, and it tracks how many names (hard links) point to this single inode. When you created filec, the link count for this inode increased from 1 to 2.
  • File Type (Column 1 of permissions): Note that filec is listed as a regular file (its permissions start with -), just like filea. It is not a special link type like fileb (which starts with l).

In this step, you will observe the critical differences in behavior between symbolic links and hard links when the original source file is removed and then recreated. This will solidify your understanding of how each type of link works. We will continue using filea, fileb, and filec in the ~/project directory.

First, let's remove the original file, filea.

rm filea

Now, let's examine the status of our three files. Use the ls -l command. You will likely see an error for filea because it no longer exists, which is expected.

ls -l file[a-c]

The output will be very revealing:

ls: cannot access 'filea': No such file or directory
lrwxrwxrwx 1 labex labex 5 May 20 10:41 fileb -> filea
-rw-r--r-- 1 labex labex 14 May 20 10:40 filec
  • Symbolic Link fileb: The link is now "broken." It still points to the name filea, but that name no longer corresponds to an existing file. In many terminals, the filename fileb will be colored red to indicate this broken state. If you try to cat fileb, you will get an error.
  • Hard Link filec: The file filec is completely unaffected. Its link count (the second column) has simply decreased from 2 to 1, but the file and its data are still intact. This is because removing filea only removed one of the names pointing to the inode; the data is not deleted until the link count drops to zero. You can prove this by viewing its content:
cat filec

The output is still the original content:

This is filea.

Now, let's recreate filea, but with different content. Use vi to create a new file named filea.

  1. Start vi: vi filea
  2. Press i to enter Insert mode.
  3. Type the new content: This is the new filea.
  4. Press Esc to return to Command mode, then type ZZ to save and exit.

With the new filea in place, let's inspect all three files again with ls -il.

ls -il file[a-c]

The output will show a new situation:

131080 -rw-r--r-- 1 labex labex 20 May 20 11:05 filea
131076 lrwxrwxrwx 1 labex labex  5 May 20 10:41 fileb -> filea
131075 -rw-r--r-- 1 labex labex 14 May 20 10:40 filec
  • New filea: A new file filea exists, but notice its inode number (e.g., 131080) is different from the inode of filec (e.g., 131075). This is a completely new file that just happens to have the same name as the old one.
  • Symbolic Link fileb: The link is no longer broken! It automatically points to the new file named filea.
  • Hard Link filec: filec is unchanged. It still points to the original inode and contains the original data.

Finally, let's check the contents of all three files to see the result.

cat filea
cat fileb
cat filec

The output clearly demonstrates the difference:

This is the new filea.
This is the new filea.
This is filea.

The symbolic link fileb followed the name to the new file, while the hard link filec maintained its connection to the original data.

Copy and Move Files with cp and mv

In this final step, you will learn to use the cp (copy) and mv (move) commands, which are essential for managing files. The cp command creates a duplicate of a file or directory, while the mv command either renames a file/directory or moves it to a different location.

Let's start by cleaning up the files from the previous steps to have a fresh workspace. All commands will be run from your ~/project directory.

rm filea fileb filec

Copying Files with cp

The cp command creates a new, independent copy of a file. The new file will have its own inode.

  1. First, create a simple file to work with using the touch command. touch creates an empty file if it doesn't exist.
touch source_file
  1. Now, let's view its properties, paying attention to the inode number (the first column).
ls -i source_file

The output will show a unique inode number for this file.

131081 source_file
  1. Next, copy source_file to a new file named copied_file.
cp source_file copied_file
  1. Now, list the properties of both files.
ls -i source_file copied_file

You will see that they are two separate files with different inode numbers.

131082 copied_file
131081 source_file

Moving and Renaming Files with mv

The mv command is versatile. If the destination is a new filename in the same directory, it renames the file. If the destination is a directory, it moves the file into it. When renaming or moving a file within the same filesystem, the inode number does not change; the command simply updates the file's name or location pointer.

  1. Let's rename source_file to renamed_file.
mv source_file renamed_file
  1. Check the inode of the newly named file.
ls -i renamed_file

You will notice that the inode number (e.g., 131081) is the same as the original source_file. The file itself wasn't changed, only its name.

131081 renamed_file
  1. Now, let's move this file. First, create a destination directory.
mkdir move_destination
  1. Move renamed_file into the move_destination directory.
mv renamed_file move_destination/
  1. Verify that the file is now inside the directory and check its inode again.
ls -i move_destination/renamed_file

The inode number remains the same, confirming that the file was moved, not copied.

131081 move_destination/renamed_file

Handling Overwrites

By default, many systems alias cp to cp -i to prevent you from accidentally overwriting an existing file. The -i stands for "interactive".

  1. Let's try to copy copied_file over the file inside our move_destination directory.
cp -i copied_file move_destination/renamed_file
  1. Because of the -i alias, you will be prompted for confirmation.
cp: overwrite 'move_destination/renamed_file'?

Type y and press Enter to confirm the overwrite. If you wanted to cancel, you would type n.

Summary

In this lab, you learned the fundamental commands for managing files and directories in a Linux environment. You practiced creating directory structures using mkdir, including the -p option for parent directories, and removing them with rmdir for empty directories and rm for non-empty ones. You also created files using the vi editor and were introduced to the concept of file linking.

The core of the lab focused on creating and analyzing the two types of links: symbolic (soft) links with ln -s and hard links with ln. You observed their key differences by examining inodes and noting how each link behaves when the source file is modified or deleted. Finally, you used the cp command to create independent copies of files and the mv command to move or rename files and directories, completing a comprehensive overview of essential file management operations.