Linux explore 13- directory operations

-----Latest update [2022-01-22]-----

Preview of this article's directory structure:

  • 1, Related concepts
    1. Absolute path and relative path
    2. Current directory
    3. Home directory
    4. Path name abbreviations: And~
  • 2, Related commands
    1. Switch and view working directory: cd, pwd
    2. Directory operations: create (mkdir), remove (rmdir), rename (mv)
    3. Directory stack: dirs, pushd, popd
    4. Display contents related to directory: ls
    5. Check file type: file
    6. Display tree: tree
  • 3, Reference

1, Related concepts

1. Absolute path and relative path

Think of the Unix file system as a big tree. The trunk is the root directory, and other directories are branches.

The pathname or path describes a location in the file tree by enumerating a sequence of directories separated by /. If the directory sequence starts from the root directory /, it is called absolute pathname. If the directory sequence starts from the working directory, it is called relative pathname.

2. Current directory

Unix allows you to specify a directory as the working directory (also known as the current directory) at a certain time.

Use the command pwd to view the current working directory:

[nosee@instance-4 ~/mygit]$ pwd
/home/nosee/mygit

3. Home directory

In Unix, each actual user will be given a home directory according to the user ID, and the user login system is in the user directory by default.

Use the command cd to switch back to the home directory from any directory:

[nosee@instance-4 ~/mygit]$ cd
[nosee@instance-4 ~]$ 

Use the command echo $HOME to view the home directory name:

[nosee@instance-4 ~]$ echo $HOME
/home/nosee

4. Path name abbreviations: And~

1) In the pathname (DOT) is also used to indicate the current directory (two dots) indicates the parent directory.
2) Multiple use You can move multiple levels up, such as.. / /.
3). And Are abbreviations, actually referring to a complete pathname.
4) In some cases, you must specify an absolute path, which can be used Abbreviation to indicate the name of the working directory.
5) ~ indicates the home directory of the current user
6) When you need to reference the home directory of another user ID, you can use: ~ user ID
7) ~ is an abstract concept provided by the shell. It is provided for the convenience of referencing the home directory. It is similar to And The implementation of is different.

2, Related commands

1. Switch and view working directory: cd, pwd

1)cd
cd - Change the shell working directory
Syntax: cd [-L|[-P [-e]] [-@]] [dir]

If - is used instead of the directory name when entering the command, the cd will switch back to the previous directory (the last accessed directory).

Common options:
-P. If the directory is a symbolic link, jump to the actual pathname.

Example:

[nosee@instance-4 /proc]$ cd
[nosee@instance-4 ~]$ cd -
/proc
[nosee@instance-4 /proc]$ 

2)pwd
pwd - displays the current print working directory

[nosee@instance-4 ~]$ pwd
/home/nosee

2. Directory operations: create (mkdir), remove (rmdir), rename (mv)

1) mkdir - create a new directory
make directories.
Syntax: MKDIR [option] directory...

Where directory is the name of the directory you want to create. When specifying the directory name to be created, you can use either absolute or relative pathnames, as well as standard abbreviations.

Example:

[nosee@instance-4 ~/test]$ mkdir dd1 ./dd2 ~/test/dd3 $HOME/test/dd4 /home/nosee/test/dd5
[nosee@instance-4 ~/test]$ ls -alF
total 28
drwxr-xr-x  7 nosee nosee 4096 Jan 20 02:28 ./
drwxr-xr-x 12 nosee nosee 4096 Jan 20 02:27 ../
drwxr-xr-x  2 nosee nosee 4096 Jan 20 02:28 dd1/
drwxr-xr-x  2 nosee nosee 4096 Jan 20 02:28 dd2/
drwxr-xr-x  2 nosee nosee 4096 Jan 20 02:28 dd3/
drwxr-xr-x  2 nosee nosee 4096 Jan 20 02:28 dd4/
drwxr-xr-x  2 nosee nosee 4096 Jan 20 02:28 dd5/

When creating a directory, we should follow two reasonable rules formulated by Unix: first, you cannot create subdirectories with the same name in a directory; Second, you cannot create a subdirectory if the parent directory does not exist.

Example: you can create parent directories and subdirectories in order in the same command. Note that the parent directory must be in front of the subdirectory

[nosee@instance-4 ~/test]$ mkdir dd6 dd6/aaa dd6/bbb dd6/ccc

Common options:

  • -p (make parent creates parent directory) when the parent directory does not exist, the parent directory will be created automatically.

Example:

[nosee@instance-4 ~/test]$ mkdir dd7/a1
mkdir: cannot create directory 'dd7/a1': No such file or directory
[nosee@instance-4 ~/test]$ mkdir -p dd7/a1
[nosee@instance-4 ~/test]$ ll dd7
total 12
drwxr-xr-x 3 nosee nosee 4096 Jan 20 02:41 .
drwxr-xr-x 9 nosee nosee 4096 Jan 20 02:41 ..
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:41 a1

2) rmdir - remove directory
Remove empty directory. (remove empty directories)
Syntax: rmdir [option] directory...

Example: remove the directories dd1, dd2, dd3, dd4 and dd5, which are empty directories (they do not contain subdirectories or files).

[nosee@instance-4 ~/test]$ ls -lF
total 28
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:50 dd1/
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:50 dd2/
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:50 dd3/
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:50 dd4/
drwxr-xr-x 2 nosee nosee 4096 Jan 20 02:50 dd5/
drwxr-xr-x 5 nosee nosee 4096 Jan 20 02:35 dd6/
drwxr-xr-x 3 nosee nosee 4096 Jan 20 02:41 dd7/
[nosee@instance-4 ~/test]$ rmdir dd[1-5]
[nosee@instance-4 ~/test]$ ls -lF
total 8
drwxr-xr-x 5 nosee nosee 4096 Jan 20 02:35 dd6/
drwxr-xr-x 3 nosee nosee 4096 Jan 20 02:41 dd7/

When removing a directory, you should follow two rules formulated by Unix: first, you cannot remove a non empty directory (if a directory contains subdirectories or files, then the directory is not empty); Second, you cannot delete any directory between the working directory and the root directory.

Note: if the current working directory is empty, it is allowed to remove the working directory, but generally not.

Common options:

  • -p. (delete parent delete parent directory) automatically remove all parent directories that need to be removed.

Example: the following rmdir -p a/b/c is equivalent to rmdir a/b/c a/b a

[nosee@instance-4 ~/test]$ ls -lF
total 0
[nosee@instance-4 ~/test]$ mkdir -p a/b/c
[nosee@instance-4 ~/test]$ ls -lF
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 03:25 a/
[nosee@instance-4 ~/test]$ rmdir -p a/b/c/
[nosee@instance-4 ~/test]$ ls -lF
total 0

Note: if you really need to delete non empty directories, you can use the rm -r command to remove all subdirectories and their contents.

3) mv - Rename (move) directory
Using the mv program, you can "move" the directory from one location to another. If the new location is in the same directory as the original, the actual result is to rename the original directory. When mv moving a directory, all files and subdirectories in the directory are moved at the same time.
mv - move (rename) files.

Syntax: MV [option] [-T] SOURCE DEST
Or MV [option] SOURCE... DIRECTORY
Or MV [option]- t DIRECTORY SOURCE...

Example:

[nosee@instance-4 ~/test]$ ls -lF
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:05 doc/
[nosee@instance-4 ~/test]$ mv doc/  text
[nosee@instance-4 ~/test]$ ls -lF
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:05 text/

If the directory already exists, mv move the original directory to the target directory, such as:

[nosee@instance-4 ~/test]$ mkdir mydoc
[nosee@instance-4 ~/test]$ ls -lF
total 8
drwxr-xr-x 2 nosee nosee 4096 Jan 20 19:08 mydoc/
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:05 text/
[nosee@instance-4 ~/test]$ mv text/ mydoc/
[nosee@instance-4 ~/test]$ ls -lF
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:09 mydoc/
[nosee@instance-4 ~/test]$ ls -lF mydoc/
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:05 text/

If the target directory already exists and there is a subdirectory with the same name in the target directory, the move will fail. For example:

[nosee@instance-4 ~/test]$ mkdir text
[nosee@instance-4 ~/test]$ mv text/ mydoc/
mv: cannot move 'text/' to 'mydoc/text': Directory not empty

mv programs can work on directories, but they can also work on files. It will be explained in detail in my next document "Linux in depth exploration 14 - file operation".

3. Directory stack: dirs, pushd, popd

Stack is a last in first out data structure. There are several built-in commands in the shell, which can handle the Linux directory similar to the stack structure. (Note: for built-in commands, you can use help built-in command or man bash to view the instructions of built-in commands)

Command introduction:
dirs - view the directory stack. (Display directory stack)
pushd - push a directory into the directory stack. (Add directories to stack)
popd - pop a directory from the directory stack. (Remove directories from stack)
Command syntax:
dirs [-clpv] [+N] [-N]
pushd [-n] [+N | -N | dir]
popd [-n] [+N | -N]

Common instructions:

command explain
dirs Display name: home directory is displayed as~
dirs -l Display name: the home directory is displayed as the full pathname
dirs -v Display name: one line for each, with digital identification
pushd directory Change the working directory: push the directory onto the stack
pushd +n Change working directory: move the directory #n to the top of the stack
popd Change working directory: pop up stack top
popd +n Remove directory from stack #n
dirs -c Remove all directories in the stack except the current working directory

Example (note the change of working directory in shell prompt):

[nosee@instance-4 ~]$ dirs -v
 0  ~
[nosee@instance-4 ~]$ pushd /etc
/etc ~
[nosee@instance-4 /etc]$ pushd /var
/var /etc ~
[nosee@instance-4 /var]$ pushd /usr
/usr /var /etc ~
[nosee@instance-4 /usr]$ pushd /lib
/lib /usr /var /etc ~
[nosee@instance-4 /lib]$ dirs -v
 0  /lib
 1  /usr
 2  /var
 3  /etc
 4  ~
[nosee@instance-4 /lib]$ dirs -l
/lib /usr /var /etc /home/nosee
[nosee@instance-4 /lib]$ pushd +3
/etc ~ /lib /usr /var
[nosee@instance-4 /etc]$ dirs -v
 0  /etc
 1  ~
 2  /lib
 3  /usr
 4  /var
[nosee@instance-4 /etc]$ popd 
~ /lib /usr /var
[nosee@instance-4 ~]$ dirs -v
 0  ~
 1  /lib
 2  /usr
 3  /var
[nosee@instance-4 ~]$ popd +1
~ /usr /var
[nosee@instance-4 ~]$ dirs -c
[nosee@instance-4 ~]$ dirs -v
 0  ~

Note:
1) At any time, the name of the working directory is stored at the top of the stack.
2) When dirs uses the option, the option must be specified separately. (for example, you can use dirs -l -v, but not dirs -lv)
3) When using pushd +n to move a directory, it looks like the entire directory stack moves upward from #n's position, and the #n previous directories move to the bottom of the stack in turn.
4) Most of the time, it is enough for us to use the command cd to move between directories, but sometimes we just switch back and forth between several fixed directories. At this time, using the directory stack is also a good experience.
5) The use principle of directory stack is actually a little similar to the historical list of shell commands.

4. Display contents related to directory: ls

ls - displays the names of the files in the directory in alphabetical order by default. (list directory contents)

1) Grammar
ls [OPTION]... [FILE]...

Common options:

  • -a. (all files) displays all files (by default, ls does not display hidden files, that is, files starting with the. Character)
  • -C. Force output as a column (such as writing to a file or pipeline)
  • -d. (directory) displays the directory as a file without viewing the interior of the directory.
  • -F. Attach the flag of file type, such as: * / = >@|
  • -h. (human readable) displays the unit of file size (kb) in a human readable manner. It is generally used in combination with - s and - l
  • -i. (lowercase I) displays the I node of the file
  • -l. (lowercase L) each line displays (enumerates) file details
  • -r. Displays the file names in reverse order
  • -R. (recursive) list all direct or indirect subdirectories and files in the directory, that is, display the information of the whole directory tree
  • -s. (size) list the file size in kilobytes before each file name
  • -t. Display files in chronological order (latest to oldest)
  • --color[=WHEN], use color to distinguish the type of file

2) Type flags - F, - l
With the - F option, the following type flags are appended to the file name:

sign meaning
nothing Ordinary file: non executive file
* Ordinary file: executable file
/ catalogue
@ Symbolic link
| name pipes

3) Option - l
Using the - l option, there will be the following indicator at the beginning of the corresponding line of each file:

Indicator meaning
- Ordinary file
d catalogue
l Symbolic connection
b Special files (block devices)
c Special file (character device)
p Named pipe / FIFO
[nosee@instance-4 ~/test]$ ls -lF
total 4
drwxr-xr-x 3 nosee nosee 4096 Jan 20 19:05 doc/

Note:
For example, d in drwxr-xr-x above represents the directory.
The time and date to the left of the file name is the last modification time of the file.

4) About file size

In a text file, a byte can hold one character (ASCII character). But in Linux, the amount of disk space used by a file is different from the amount of data in the file.

For example, create a text file with only one character

[nosee@instance-4 ~]$ cat > a
a
^C
[nosee@instance-4 ~]$ ls -lsh a
4.0K -rw-r--r-- 1 nosee nosee 2 Jan 21 13:18 a

As can be seen from the above example, file a contains data of 2 bytes (B), but the file occupies 4KB of storage space.

This is because in the file system, space is allocated in fixed size blocks, which we call blocks. Depending on the file system, the block size can be 521B, 1KB, 2KB or 4KB. The minimum disk space allocated for a file is a block. Even a file containing only 1 byte will occupy a block.

be careful:
The size in front of the directory refers to the size of the directory itself, not the size of the contents of the directory.
In fact, the directory only contains the name of the file and the I node number of the file. Therefore, the contents of the directory are quite small: there is only one column of names, and each name corresponds to an i node number.

5)--color
--color option Description:
Many linux will set alias ls='ls --color=auto 'in the configuration file by default

Using colors to distinguish different file types, the following commands are equivalent:

ls --color
ls --color=always
ls --color=yes
ls --color=force

Turn off color usage:

ls --color=never
ls --color=no
ls --color=none

Typically, special codes that create colors are mixed in the output. This will not be a problem when output on the display. However, when the output is sent to a pipeline or file, the information may be a little messy. To avoid this, you can tell the ls command to use the color only when the output is to be displayed on the terminal by setting the -- color device to auto. The following commands are also equivalent:

ls --color=auto
ls --color=tty
ls --color=if-tty

Using the command ls --color=yes | less, you can find the special codes of these colors:

letter.txt
ESC[0mESC[01;34mmygitESC[0m
ESC[01;31mmysql-apt-config_0.8.20-1_all.debESC[0m
pr_info.txt
sorttest
ESC[01;34mtestESC[0m
uuu.txt
ESC[01;34mwwwESC[0m

Note: for color configuration information, you can view the environment variable LS_COKORS or use the command dircolors to view. If you want to customize your own colors, you can use the specific dircolors command to generate a setting line_ Cokors command, and then use this command in the initial configuration file.

6) Wildcard
When you need to specify a vague file name or directory name after using the ls command, you can use a specific metacharacter -- wildcard.

Note: here, the meaning of these wildcards is different from that in regular expressions.

Symbol meaning
* Match 0 or more arbitrary characters (except /, because this is the delimiter in the pathname)
? Match any 1 characters (Note: not 0 or 1)
[list] Match any 1 character in the list
[^list] Match any 1 character that is not in the list
[n-m] Matches 1 character in the specified character range, such as [a-z], [0-9]
{string1|string2} Matches one of the specified strings
{string1,string2} Match the strings in braces in turn

Note: if a directory is matched, it is equivalent to ls directory, and the directory will be opened.

7) Case description

Example 1: default

[nosee@instance-4 ~]$ ls /
bin   dev  home  lib32  libx32      media  opt   root  sbin  sys  usr
boot  etc  lib   lib64  lost+found  mnt    proc  run   srv   tmp  var

Note that by default, files are sorted alphabetically as columns. In other words, read the document vertically rather than horizontally.

However, when redirecting the output of ls to a file or pipeline, ls outputs the result as one line per file. For example:

[nosee@instance-4 ~]$ ls / | wc -l
22

Example 2: display the entire directory tree under the specified directory

[nosee@instance-4 ~/test]$ ls -R
.:
A  Z  a  mydoc  z

./mydoc:
haha.txt  text

./mydoc/text:
a

./mydoc/text/a:
b

./mydoc/text/a/b:

5. Check file type: file

File - determines the file type. (determine file type)

Although using ls to view the directory can also view the simple types of files at the same time, using the file command can get more detailed file types.

1) Common cases
Example:

[nosee@instance-4 ~]$ file www
www: directory
[nosee@instance-4 ~]$ file uuu.txt 
uuu.txt: ASCII text
[nosee@instance-4 ~]$ file sorttest 
sorttest: UTF-8 Unicode text
[nosee@instance-4 ~]$ file mysql-apt-config_0.8.20-1_all.deb 
mysql-apt-config_0.8.20-1_all.deb: Debian binary package (format 2.0)
[nosee@instance-4 ~]$ file /bin
/bin: symbolic link to usr/bin

View multiple files simultaneously:

[nosee@instance-4 ~]$ file www uuu.txt sorttest mysql-apt-config_0.8.20-1_all.deb /bin
www:                               directory
uuu.txt:                           ASCII text
sorttest:                          UTF-8 Unicode text
mysql-apt-config_0.8.20-1_all.deb: Debian binary package (format 2.0)
/bin:                              symbolic link to usr/bin

View all files in the specified directory:

[nosee@instance-4 ~]$ file www/*
www/hi.php:                 PHP script, ASCII text
www/index.html:             UTF-8 Unicode text
www/mygit-site:             directory
www/mysql_connect_test.php: PHP script, UTF-8 Unicode text
www/phpinfo.php:            PHP script, UTF-8 Unicode text
www/thinkphp-1:             directory
www/thinkphp-2:             directory
www/thinkphp-3:             directory
www/thinkphp-4:             directory

2) View executable
When viewing an executable file, you will get longer information (usually for programmers and system administrators).
For example (because the output is too long, you can format the output with the command fold or fmt):

[nosee@instance-4 /usr/bin]$ file ls
ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=a65f86cd6394e8f583c14d786d13b3bcbe051b87, stripped
[nosee@instance-4 /usr/bin]$ file ls | fold
ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked,
 interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=a65
f86cd6394e8f583c14d786d13b3bcbe051b87, stripped

Executable file information interpretation:
ELF: Executable and Linking Format, the standard format of executable files.
64 bit: word length.
LSB: compiled with Least Significant Byte word order and used by x86 processor.
Executable: executable file.
version 1 (SYSV): the version of the internal file format.
dynamically linked: use shared libraries instead of static links.
GNU/Linux 3.2.0: the operating system and kernel version of the compiler.
stripped: the executable file to remove the symbol table (reduce the size of the executable file).

6. Display tree: tree

There is a powerful tool tree in Linux, which can draw the graphics of any part of the file system. (some systems do not install the program by default, so sudo apt get install tree needs to be installed manually.)

tree - list contents of directories in a tree-like format

Example: there is no tree with any options by default

[10:12 @nosee ~]$ tree
.
├── Desktop
│   └── test1
├── Documents
├── Downloads
├── Music
├── Pictures
├── Public
├── snap
│   └── snap-store
│       ├── 518
│       ├── 558
│       ├── common
│       └── current -> 558
├── Templates
├── Videos
└── desktop
    ├── my_host
    └── New text document.txt

15 directories, 3 files

The tree program has many options, several of which have the same meaning as the option with the same name in the ls command. For example: - a, - s, - F, - r and - t.
Other common options:

  • -d. Show directory only
  • -f. Displays the full pathname
  • -i. Omit indentation when outputting results
  • -L level, which specifies the depth of the tree. Level is a number
  • -l. (lowercase L) follow all symbolic links

3, Reference

Bookcase: Chapter 24 of UNIX & Linux University Course (US): Harley Hahn, translated by Zhang Jieliang

Keywords: Linux Unix

Added by dancingbear on Tue, 25 Jan 2022 14:45:45 +0200