File and Directory

LinuxLinuxBeginner
Practice Now

Introduction

This lab will introduce basic concepts of Linux directory structure, absolute path, relative path, and cut, copy, rename, edit, and other file operations. Like other labs, you will accomplish all of those through hands-on practices and exercises.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/UserandGroupManagementGroup(["`User and Group Management`"]) linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) linux(("`Linux`")) -.-> linux/ProcessManagementandControlGroup(["`Process Management and Control`"]) linux/BasicFileOperationsGroup -.-> linux/cat("`File Concatenating`") linux/BasicFileOperationsGroup -.-> linux/tail("`File End Display`") linux/BasicFileOperationsGroup -.-> linux/more("`File Scrolling`") linux/BasicSystemCommandsGroup -.-> linux/tree("`Directory Tree Display`") linux/PackagesandSoftwaresGroup -.-> linux/apt("`Package Handling`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/FileandDirectoryManagementGroup -.-> linux/pwd("`Directory Displaying`") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("`Directory Creating`") linux/BasicFileOperationsGroup -.-> linux/cp("`File Copying`") linux/BasicFileOperationsGroup -.-> linux/mv("`File Moving/Renaming`") linux/BasicFileOperationsGroup -.-> linux/rm("`File Removing`") linux/UserandGroupManagementGroup -.-> linux/sudo("`Privilege Granting`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/VersionControlandTextEditorsGroup -.-> linux/vim("`Text Editing`") linux/ProcessManagementandControlGroup -.-> linux/bg_running("`Background Running`") subgraph Lab Skills linux/cat -.-> lab-17997{{"`File and Directory`"}} linux/tail -.-> lab-17997{{"`File and Directory`"}} linux/more -.-> lab-17997{{"`File and Directory`"}} linux/tree -.-> lab-17997{{"`File and Directory`"}} linux/apt -.-> lab-17997{{"`File and Directory`"}} linux/cd -.-> lab-17997{{"`File and Directory`"}} linux/pwd -.-> lab-17997{{"`File and Directory`"}} linux/mkdir -.-> lab-17997{{"`File and Directory`"}} linux/cp -.-> lab-17997{{"`File and Directory`"}} linux/mv -.-> lab-17997{{"`File and Directory`"}} linux/rm -.-> lab-17997{{"`File and Directory`"}} linux/sudo -.-> lab-17997{{"`File and Directory`"}} linux/touch -.-> lab-17997{{"`File and Directory`"}} linux/vim -.-> lab-17997{{"`File and Directory`"}} linux/bg_running -.-> lab-17997{{"`File and Directory`"}} end

FHS Standard

Directory Structure in Linux

While the general operations of Windows and Linux are similar, their implementation mechanisms are fundamentally different, particularly in the relationship between directory and storage media; Windows uses disk icons for file management, leading to potentially disorderly file storage, whereas Linux's directory-based approach allows for a more organised and structured file management system, with the ability to mount disk partitions and network file systems on directories.

FHS Logic

The basic logic behind the Linux directory is that the regular operation of the system is based on a directory structure. In most cases, beginners need to learn the role of most directories in Linux, especially those who have used only Windows before. They would be confused about where they installed software packages. However, after you've familiarized yourself with Linux, you will find it much simpler and more convenient than you imagine. The directory structure in Linux has been set (FHS standard). Once you have understood the principles of Linux, all your operations on the system will be organized and neat.

FHS (Filesystem Hierarchy Standard): Most Linux versions use this file structure. FHS defines the use of every area in the system, the minimal set of required files and directories, and also provides exception handling and contradiction handling.

FHS defines two specifications:

  1. The various directories below / should contain specific files, such as setting files should be placed in the directory /etc, and executable files should be placed in /bin and /sbin.
  2. There are explicit definitions of the subdirectories of the two directories /usr and /var, such as/var/log to place the system log files and /usr/share to place shared data.

If you think the picture is blurry, you can save it and zoom over it in View settings:

You can also execute the following command to view the entire directory structure:

tree /

View the result:

...
── www
└── html
├── index.html
└── index.nginx-debian.html

33008 directories, 303799 files

Directory Path

What "Path" is

The path in Linux represents the route to specific directories or files, with symbols such as . for the current directory, .. for the parent directory, - for the last used directory, and ~ for the current user's home directory, while the pwd command retrieves the current absolute path.

Go to the upper directory:

cd ..

Go to your home directory:

cd ~

Use pwd to get the current path:

pwd

Absolute Path

The absolute path contains the root directory and all other subdirectories contained in a file or directory. For example: /usr/local/bin indicates the 'bin' directory in the 'local' directory in the 'usr' directory of the root ('/') directory.

Relative Path

Relative path is relative to the current working directory (pwd). Suppose I am located in /var/log and I want to change the directory to /var/log/kernel. I can use the relative path concept to change the directory to kernel.

Changing the directory to /usr/local/bin by using the relative path concept:

cd ~
cd ../../usr/local/bin

View the example:

labex:project/ $ cd ~
cd ../../usr/local/bin
labex:bin/ $ pwd
/usr/local/bin

Whether you use an absolute path or a relative path, you can go to another directory.

Tip: In switching directories, please use Tab to automatically fill the path, which can avoid input errors. Press Tab twice to show all results.

Create

To Create a New File

The following commands will create an empty file named "test". Because you do not have permission in other directories, you need to use cd ~/project to switch back to the user's /home/labex directory:

cd ~/project
touch test

To Create a New Directory

The command mkdir (make directories) can create an empty directory. You can also specify the permission attribute of the directory.

Creating an empty directory named "mydir":

mkdir mydir

Using mkdir with the -p parameter can create the parent directory if the parent directory does not exist. We create multi-level directories (this is useful when installing software and configuring installation paths):

mkdir -p father/son/grandson

View the result:

labex:project/ $ cd father/son/grandson
labex:grandson/ $ pwd
/home/labex/project/father/son/grandson

Copy

To Copy Files

You can use cp to replicate a file to the specified directory.

Copy the previously created "test" file to "/home/labex/proj/father/son/grandson" :

cp test father/son/grandson

View the output:

labex:project/ $ pwd
/home/labex/project
labex:project/ $ cp test father/son/grandson
labex:project/ $ ll father/son/grandson/test
-rw-rw-r-- 1 labex labex 0 Feb 19 14:30 father/son/grandson/test

Copy directories

The following error will occur when you directly use the cp to copy a directory:

mkdir family
cp father family

View cp: -r not specified; omitting directory 'father' in the terminant

cp with -r or -R parameter can work. The parameter represents recursive copy:

cp -r father family

View the structure of the directory:

labex:project/ $ tree family
family
└── father
    └── son
        └── grandson
            └── test

3 directories, 1 file

Delete

To Delete Files

Use the command rm to delete a file:

rm test

If you want to ignore this prompt and delete the file directly, you can use the -f parameter to force the deletion:

rm -f test

To Delete Directories

As with copying a directory, to delete a directory, also you need to add the -r or -R parameter:

rm -r family

Move and Rename

To Move Files

The command mv can move a file to another place. Move "file1" to the directory named "Documents":

mkdir Documents
touch file1
mv file1 Documents

View the result:

labex:project/ $ mkdir Documents
labex:project/ $ touch file1
labex:project/ $ ls file1
file1
labex:project/ $ mv file1 Documents
labex:project/ $ cd Documents
labex:Documents/ $ ls
file1

To Rename a File

Rename the file "file1" to "myfile":

mv file1 myfile

To View Files

The cat command usage

The cat command prints file contents to standard output (terminal) in forward order, while the tac command prints contents in reverse order. In addition, when a shell command is executed, the system automatically opens three standard files: standard input (stdin), standard output (stdout), and standard error output (stderr), which handle input, output, and error messages for the process, respectively.

For example, we can view the file passwd in the /etc directory:

sudo cat /etc/passwd

You can add the -n parameter to display the line number:

sudo cat -n /etc/passwd
labex:project/ $ sudo cat -n /etc/passwd
1 root:x:0:0:root:/root:/bin/bash
2 daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
3 bin:x:2:2:bin:/bin:/usr/sbin/nologin
4 sys:x:3:3:sys:/dev:/usr/sbin/nologin
5 sync:x:4:65534:sync:/bin:/bin/sync
...

more and less

The less is a more advanced and versatile pager than the more. It allows both forward and backward navigation within files, and does not require the entire input file to be read before starting, resulting in faster startups with large input files. It also makes less use of termcap (or terminfo on some systems), allowing it to run on a variety of terminals, and even provides limited support for hardcopy terminals. Its command interface is based on both more and vi, providing advanced functionality with the flexibility to use decimal numbers for certain commands.

Use more to open the passwd:

sudo more /etc/passwd
labex:project/ $ sudo more /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin

You can use Enter to scroll down one line, Space to scroll down one screen, h to display the help, and q to exit.

To Use head and tail to View a File

head displays the first count lines or bytes of each of the specified files or the standard input if no files are selected. If count is omitted, it defaults to 10. tail is similar to head. The difference is that the tail displays the last count of lines of files. For example, we want to view the information of new users, and, as we all know, the latest information must be at the end of the file. In this case, we can use tail to view it:

sudo tail /etc/passwd
labex:project/ $ sudo tail /etc/passwd
usbmux:x:107:46:usbmux daemon,,,:/var/lib/usbmux:/usr/sbin/nologin
rtkit:x:108:113:RealtimeKit,,,:/proc:/usr/sbin/nologin
...

To View File Types

As we mentioned before, the file type in Linux is not based on the filename suffix. We need to use file to view the file type:

file /bin/ls
labex:Documents/ $ file /bin/ls
/bin/ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=897f49cafa98c11d63e619e7e40352f855249c13, for GNU/Linux 3.2.0, stripped

This executable file can run on a 64-bit platform and uses a dynamic link file (shared library).

To Edit Files

In Linux, we usually use command-line editors to edit files, such as emacs, vim, and nano. We have another course introducing vim. It is highly recommended that you first study the vim editor before continuing to study this course. If you want to expedite your learning progress, you can use the Linux internal vim tutorial. Enter the following command to start it:

vimtutor

View the part of command-line editors in the terminant:

===============================================================================
= W e l c o m e t o t h e V I M T u t o r - Version 1.7 =
===============================================================================

Vim is a very powerful editor that has many commands, too many to
explain in a tutor such as this. This tutor is designed to describe
enough of the commands that you will be able to easily use Vim as
an all-purpose editor.

The approximate time required to complete the tutor is 30 minutes,
depending upon how much time is spent with experimentation.

Addition

Do you believe you'll subconsciously feel pressured when learning? If someone is watching you, you must learn faster. Today, I'll teach you how to summon a pair of eyes to supervise you:

xeyes

You can use the following command to put it in the background to run:

nohup xeyes &
image desc

Summary

Passing the lab, you learn basic concepts of Linux directory structure, absolute path, relative path, and cut, copy, rename, edit, and other file operations. You also learn how to use the Linux terminal, including basic navigation, file navigation, and command-line arguments.

Other Linux Tutorials you may like