- Linux cd command
- Description
- Syntax
- Options
- Directories
- How directories are represented
- The root directory
- The working directory
- The parent directory
- Your home directory
- The previous working directory
- Using a trailing slash
- Examples
- Related commands
- Команда cd в Linux (Изменить каталог)
- cd Command
- Абсолютные и относительные имена путей
- Родительский каталог
- Перейти в предыдущий каталог
- Перейдите в домашний каталог
- Каталоги с пробелами в именах
- Выводы
- 15 Practical Examples of ‘cd’ Command in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Linux cd command
On Unix-like operating systems, the cd command («change directory») changes the shell’s current working directory.
This page covers the bash built-in version of cd.
Description
cd is among the commands you use most often on the command line. It changes your working directory. Use it to move around in the hierarchy of your file system.
Syntax
Options
-L | Force symbolic links to be followed. In other words, if you tell cd to move into a «directory», which is actually a symbolic link to a directory, it moves into the directory the symbolic link points to. This option is the default behavior of cd; normally, it always acts as if -L was specified. |
-P | Use the physical directory structure without following symbolic links. In other words, only change into the specified directory if it actually exists as named; symbolic links are not followed. This option is the opposite of the -L option, and if they are both specified, this option is ignored. |
-e | If the -P option is specified, and the current working directory cannot be determined, this option tells cd to exit with an error. If -P is not specified with this option, this option has no function. |
Directories
To help you organize your files, your file system contains special files called directories. Think of them like folders in a file cabinet: they have names, like files, but their function is to «contain» other files, and other directories. In this way, you can keep the files on your system separate and sorted according to their function or purpose.
All files and directories on your system stem from one main directory: the root directory. There are no directories «above» the root directory; all other directories are «below» the root directory.
Any directory contained inside another directory is called a subdirectory. Subdirectories «branch» off the «root» of the directory «tree.» Unlike a real tree, directory trees are upside-down: the root is at the top and the branches reach down. When you move into a subdirectory, you are moving «down» the tree; when you move into a directory’s parent directory, you are moving «up» the tree.
All directories on your file system are subdirectories of the root directory.
By default, when you open a terminal and begin using the command line, you are placed in your home directory.
How directories are represented
Directories are separated by a forward slash («/«). For instance, the directory name «documents/work/accounting» means «the directory named accounting, which is in the directory named work, which is in the directory named documents, which is in the current directory.»
To change into this directory, and make it our working directory, we would use the command:
If the first character of a directory name is a slash, that denotes that the directory path begins in the root directory. So, in contrast to the example above, the directory name «/documents/work/accounting» (note the beginning slash) means «the directory named accounting, which is in the directory named work, which is in the directory named documents, which is in the root directory.»
To change into this directory, making it our working directory, we would use the command:
The root directory
The root directory is the first directory in your filesystem hierarchy. All other directories are subdirectories of the root directory.
The root directory is represented by a single slash («/«).
To change into the root directory, making it your working directory, use the command:
You cannot make any changes to the root directory on your system unless you are logged in as root, or using the sudo command. Unless you are certain of what you’re doing, don’t make any changes here. Making a mistake could destroy your system!
The working directory
The current directory, regardless of which directory it is, is represented by a single dot («.»).
So, running this command:
. would change us into the current directory. In other words, it would do nothing.
What’s actually happening is the dot represents the «assumed» directory; it’s a placeholder, and you can use the dot anywhere in a directory name. So, the command:
. is the same as the command:
. and also the same as:
In all of these examples, the dot represents «the directory assumed to be there». You can use it as a placeholder anywhere you want to tell the shell that a directory goes in that place, and to assume the appropriate value.
The parent directory
The parent directory of the current directory — in other words, the directory one level up from the current directory, which contains the directory we’re in now — is represented by two dots («..«).
So, If we were in the directory /home/username/documents, and we executed the command:
. we would be placed in the directory /home/username.
The double-dot («..») directory notation can be used anywhere in a directory name to represent going up one level. For instance, if we have two directories, /home/username/documents and /home/username/downloads, and we are currently in /home/username/documents, we could type the following:
. and we would be placed in /home/username/downloads.
Another «useless» command, but one that illustrates the way you can use the double-dot notation, is this one:
. which will place us in the directory one level above the subdirectory documents — in other words, the current directory. Note that this only work if the subdirectory documents already exists.
Similarly, the command:
. is functionally the same as this command:
Your home directory
Your home directory is the directory you’re placed in, by default, when you open a new terminal session. It’s the directory that holds all your settings, your mail, your default documents and downloads folder, and other personal items. It has a special representation: a tilde («
So, if our username is username, and our home directory is /home/username, the command:
. is functionally the same as the command:
. and we can always access the subdirectories of our home directory by placing the tilde as the first component of the directory name. For instance, if your documents folder is named /home/username/documents, you can always move into that directory using the command:
The previous working directory
After you change directory, you can change back to the previous working directory by representing it with a dash («—«). When you do this, the shell automatically tells you the new directory name.
So, for instance:
Using a trailing slash
Using a slash at the end of a directory name is optional. Directories are treated as files, so you don’t need to put it there; but if you do put it there, the system knows for sure you’re expecting that file to be a directory. For example, if there is a subdirectory in the current directory named dirname, the command:
. is the same as the command:
The second form of the command explicitly states that dirname is a directory, but both commands are equivalent.
Examples
The above example would change the working directory to the hope subdirectory if it exists.
The above example would traverse up one level to the parent directory and then down into the directory computerhope.
Traverse two directories up the directory tree. In other words, move into the directory which contains the directory which contains the current working directory.
Related commands
pwd — Print the name of the working directory.
ln — Create a link, or a symbolic link, to a file or directory.
mkdir — Create a directory.
rmdir — Remove a directory.
Источник
Команда cd в Linux (Изменить каталог)
Команда cd («изменить каталог») используется для изменения текущего рабочего каталога в Linux и других Unix-подобных операционных системах. Это одна из самых основных и часто используемых команд при работе в терминале Linux.
Текущий рабочий каталог — это каталог (папка), в котором в данный момент работает пользователь. Каждый раз, когда вы взаимодействуете с командной строкой, вы работаете в каталоге.
В этом руководстве мы покажем вам, как использовать команду cd для навигации по дереву каталогов вашей системы.
cd Command
cd — это встроенная оболочка, и ее поведение может немного отличаться от оболочки к оболочке. Он использует переменные среды оболочки для определения необходимой информации для его выполнения.
Мы рассмотрим встроенную в Bash версию cd .
Синтаксис команды cd следующий:
Команда принимает только две опции, которые используются редко.
- −L , переходить по символическим ссылкам . По умолчанию cd ведет себя так, как если бы указана опция -L .
- −P , не переходите по символическим ссылкам. Другими словами, когда эта опция указана, и вы пытаетесь перейти к символической ссылке, которая указывает на каталог, cd перейдет в каталог.
В простейшей форме, при использовании без аргументов, cd перенесет вас в ваш домашний каталог.
При навигации по файловой системе вы можете использовать клавишу Tab для автозаполнения имен каталогов. Добавление косой черты в конце имени каталога необязательно.
Чтобы переключиться в каталог, у вас должны быть разрешения на выполнение для этого каталога.
Команда pwd позволяет узнать, в каком каталоге вы сейчас находитесь.
Абсолютные и относительные имена путей
При указании каталога для перехода вы можете использовать абсолютные или относительные пути. Абсолютный или полный путь начинается с системного корня / , а относительный путь начинается с вашего текущего каталога.
По умолчанию, когда вы входите в систему Linux, вашим текущим рабочим каталогом становится домашний каталог. Предполагая, что каталог Downloads существует в вашем домашнем каталоге, вы можете перейти к нему, используя относительный путь к каталогу:
Вы также можете перейти в тот же каталог, используя его абсолютный путь:
Короче говоря, если путь начинается с косой черты ( / ), это абсолютный путь к каталогу.
Родительский каталог
В Unix-подобных операционных системах текущий рабочий каталог представлен одной точкой ( . ). Две точки ( .. ), одна за другой, представляют родительский каталог или, другими словами, каталог, расположенный непосредственно над текущим.
Если вы наберете cd . , вы перейдете в текущий каталог или, другими словами, команда ничего не сделает.
Предположим, вы находитесь в каталоге /usr/local/share , чтобы переключиться в каталог /usr/local (на один уровень выше текущего каталога), вы должны ввести:
Чтобы переместиться на два уровня вверх в каталог /usr (родительский родитель), вы можете запустить следующее:
Другой пример. Допустим, вы находитесь в каталоге /usr/local/share и хотите перейти в каталог /usr/local/src . Вы можете сделать это, набрав:
Перейти в предыдущий каталог
Чтобы вернуться в предыдущий рабочий каталог, передайте символ тире ( — ) в качестве аргумента команды cd:
Перейдите в домашний каталог
Чтобы перейти в домашний каталог, просто введите cd . Другой способ вернуться прямо в домашний каталог — использовать символ тильды (
), как показано ниже:
Например, если вы хотите перейти в каталог Downloads , который находится внутри вашего домашнего каталога, вы должны ввести:
Вы также можете перейти в домашний каталог другого пользователя, используя следующий синтаксис:
Каталоги с пробелами в именах
Если в имени каталога, в который вы хотите перейти, есть пробелы, вы должны либо заключить путь в кавычки, либо использовать символ обратной косой черты ( ), чтобы избежать пробела:
Выводы
К настоящему времени вы должны хорошо понимать, что такое текущий рабочий каталог и как использовать команду cd для перехода в другой каталог.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
15 Practical Examples of ‘cd’ Command in Linux
In Linux ‘cd‘ (Change Directory) command is one of the most important and most widely used command for newbies as well as system administrators. For admins on a headless server, ‘cd‘ is the only way to navigate to a directory to check log, execute a program/application/script and for every other task. For newbie it is among those initial commands they make their hands dirty with.
15 cd command examples in linux
Thus, keeping in mind, we here bringing you 15 basic commands of ‘cd‘ using tricks and shortcuts to reduce your efforts on the terminal and save time by using these known tricks.
Tutorial Details
- Command Name : cd
- Stands for : Change Directory
- Availability : All Linux Distribution
- Execute On : Command Line
- Permission : Access own directory or otherwise assigned.
- Level : Basic/Beginners
1. Change from current directory to /usr/local.
2. Change from current directory to /usr/local/lib using absolute path.
3. Change from current working directory to /usr/local/lib using relative path.
4. (a) Switch back to previous directory where you working earlier.
4. (b) Change Current directory to parent directory.
5. Show last working directory from where we moved (use ‘–‘ switch) as shown.
6. Move two directory up from where you are now.
7. Move to users home directory from anywhere.
8. Change working directory to current working directory (seems no use of in General).
9. Your present working Directory is “/usr/local/lib/python3.4/dist-packages/ ”, change it to “/home/avi/Desktop/ ”, in one line command, by moving up in the directory till ‘/’ then using absolute path.
10. Change from current working directory to /var/www/html without typing in full using TAB.
11. Navigate from your current working directory to /etc/v__ _, Oops! You forgot the name of directory and not supposed to use TAB.
Note: This will move to ‘vbox‘ only if there is only one directory starting with ‘v‘. If more than one directory starting with ‘v‘ exist, and no more criteria is provided in command line, it will move to the first directory starting with ‘v‘, alphabetically as their presence in standard dictionary.
12. You need to navigate to user ‘av‘ (not sure if it is avi or avt) home directory, without using TAB.
13. What are pushd and popd in Linux?
Pushd and popd are Linux commands in bash and certain other shell which saves current working directory location to memory and bring to the directory from memory as current working directory, respectively as well as changes directory.
The above command saves the current location to memory and changes to the requested directory. As soon as popd is fired, it fetch the saved directory location from memory and makes it current working directory.
14. Change to a directory containing white spaces.
15. Change from current working directory to Downloads and list all its settings in one go.
This is our attempt, to make you aware of Linux Workings and executions in least possible words and with as much as user friendliness as it used to be before.
That’s all for now. I’ll be here again with another interesting topic soon. Till then stay tuned and connected to Tecmint. Don’t forget to provide us with your valuable feedback in the comments below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник