An example of how to use CD command to switch directories in Linux

Time:2020-1-21

CD command is very familiar to you. Bash shell is often used to switch directories. Next, we can understand CD command directly through omnipotent man

No manual entry for CD will be displayed. CD is one of the basic bash commands, so it should be man bash
Man and man page will be introduced in Linux shell command: man
You can see the command syntax of Cd in man page as follows

Copy code

The code is as follows:

cd [-L|[-P [-e]] [[email protected]]] [dir]

Basic function
The function of the CD command is to jump from the current directory to dir. If the dir is left blank, it will jump to the value set in the environment variable home

Additional content

Environment variable cdpath
For the environment variable cdpath,
If cdpath is not set, the jump directory for each CD lookup is the current directory as the parent directory
If cdpath is set, the jump directory for each CD lookup is to look up the set directory as the parent directory
e. G. suppose there is a directory structure: ~ / A / B / C if cdpath is not set

Copy code

The code is as follows:

[email protected]:~$ cd a
[email protected]:~/a$ cd c
bash: cd: c: No such file or directory

If cdpath is set to cdpath =. / home / luckyshq / A / b

Copy code

The code is as follows:

Setting common directory to cdpath can improve the efficiency of CD effectively
The directories in cdpath are separated by
If you do not add. Path (that is, the current path), the previous default directory CD as the parent directory is not available
If the dir starts with / (i.e. absolute path), cdpath will fail

Cd-p, – e parameter
Enter the actual directory of shortcut directory. E.g. assume that ~ directory has two directories A and B, and a subdirectory B connected to B (this B is the shortcut)

Copy code

The code is as follows:

//Without – P parameter
[email protected]:~$ cd a
[email protected]:~/a$ cd b
[email protected]:~/a/b$
//Add – P parameter
[email protected]:~$ cd a
[email protected]:~/a$ cd -P b
[email protected]:~/b$

If you put a folder’s own shortcut in the folder, there may be infinite loops when writing scripts, and the current path name will become infinite, but with the – P command, you can avoid the situation of wireless loops
If you add – E after – P, if there is no corresponding physical path in the path before jump (for example, path with multiple shortcuts as names), it will return a failed state. (the specific usage of – E may be realized only when shell programming.)

CD -L parameter
-L parameter and – P are opposite (they can’t appear at the same time, i.e. – l| – P). They jump to the linked directory, similar to CD without parameters

..
If… Appears in dir,
If there is a path after.. then the first directory element in the path (for example, CD.. / A / B / C is equivalent to CD B / C)
If there is no path after.. then it will return to the parent directory of the current path