- Команда CD в Linux (Change Directory)
- Cd Command in Linux (Change Directory)
- В этом руководстве мы покажем вам, как использовать cd команду для навигации по дереву каталогов вашей системы.
- CD команда
- Абсолютные и относительные имена путей
- Родительский каталог
- Перейти к предыдущему каталогу
- Перейдите в Домашний каталог
- Каталоги с пробелом в их именах
- Вывод
- How to change directory in Linux terminal
- How to change directory in Linux terminal
- How to use the Linux command line to change directory or folder
- How to print the current working directory in Linux
- cd command in Linux termianl
- Absolute vs Relative pathname
- Understanding . and .. directories
- How can I return directly to my home directory when using the Linux terminal?
- How do I change directories in the Linux terminal and return to the previous directory?
- A note about symbolic links and cd command
- Linux cd command cheat sheet
- Conclusion
- How to change directory in Linux using cd command
- How to change directory in Linux
- Changes the current directory in Linux
- How do I go back to my home folder or directory in Linux?
- How to change a folder in Linux
- Linux change directory and symbolic links
- Shell environment variables
- A note about the autocd option
- Autocorrect errors/typos of a folder name
- Change directory to an external disk
- 2 Answers 2
Команда CD в Linux (Change Directory)
Cd Command in Linux (Change Directory)
В этом руководстве мы покажем вам, как использовать cd команду для навигации по дереву каталогов вашей системы.
Команда cd («изменить каталог») используется для изменения текущего рабочего каталога в Linux и других Unix-подобных операционных системах. Это одна из самых основных и часто используемых команд при работе на терминале Linux.
Текущий рабочий каталог является каталогом (папка) , в котором пользователь в настоящее время работает в. Каждый раз , когда вы взаимодействуете с вашей командной строкой, вы работаете в директории.
CD команда
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 . Вы можете сделать это, набрав:
Перейти к предыдущему каталогу
Чтобы вернуться к предыдущему рабочему каталогу, передайте — символ dash ( ) в качестве аргумента команде cd:
Перейдите в Домашний каталог
Чтобы перейти к вашему домашнему каталогу, просто введите cd . Другой способ вернуться непосредственно в ваш домашний каталог — использовать
символ tilde ( ), как показано ниже:
Например, если вы хотите перейти к Downloads каталогу, который находится внутри вашего домашнего каталога, вы должны набрать:
Вы также можете перейти к домашнему каталогу другого пользователя, используя следующий синтаксис:
Каталоги с пробелом в их именах
Если в каталоге, который вы хотите изменить, в имени есть пробелы, вы должны либо заключить путь в кавычки, либо использовать \ символ обратной косой черты ( ), чтобы убрать пробел:
Вывод
К настоящему времени вы должны хорошо понимать, что является текущим рабочим каталогом и как использовать cd команду для перехода в другой каталог.
Источник
How to change directory in Linux terminal
M y Dell Laptop came preinstalled with Ubuntu Linux, and I am a new Linux desktop user. How do I change directories in the Linux terminal?
Introduction – On Linux the cd command allows you to change directories when using the terminal application. This page shows how to change directory in Linux terminal using the cd command.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux terminal |
Est. reading time | 3 minutes |
How to change directory in Linux terminal
- To return to the home directory immediately, use cd
OR cd
Let us see all examples and usage for terminal in details.
How to use the Linux command line to change directory or folder
The directory in which the user is currently working is called the current working directory (CDW).
How to print the current working directory in Linux
To display the name of the current/working directory, type the following pwd command:
pwd
cd command in Linux termianl
The syntax is:
cd
cd ..
cd /path/to/dir
When cd command used without stipulating any directory name, cd command returns to the home directory. Let us change the directory to /usr/sbin/, run:
cd /usr/sbin/
Verify it:
pwd
Want to list the files in the /usb/sbin/ directory? Try the ls command:
ls
ls -l
Let us go back to user’s home directory, run:
cd
Again verify it:
pwd
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Absolute vs Relative pathname
The cd command changes the current directory when a directory name provided by the user. The name can be written as an absolute pathname (e.g. cd /etc/httpd/ ) or as local pathname relative to the root directory (e.g. cd conf.d/ ). For example:
cd /etc/httpd/
pwd
ls
cd conf.d/
pwd
ls
The absolute vs. relative pathname for cd command in Linux
Understanding . and .. directories
On Linux the current directory is represented by a single dot ( . ) and two consecutive dots represent its parent directory ( .. ). Thus, to change to the parent of the current directory, run cd . .. For example:
ls
pwd
cd ..
pwd
ls
How can I return directly to my home directory when using the Linux terminal?
How do I change directories in the Linux terminal and return to the previous directory?
Simply pass the — option to the cd:
cd —
Verify it:
pwd
A note about symbolic links and cd command
The -P option instructs cd to use the physical directory structure instead of following symbolic links:
cd -P LinkDir
pwd
The -L option forces cd to follow symbolic links:
cd -L LinkDir
pwd
Linux cd command cheat sheet
Command | Description |
---|---|
cd | Returns you to your login directory |
cd |
tom
Conclusion
The cd command is used to change the current directory in both Linux and other Unix-like systems. See Cd command wiki page.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to change directory in Linux using cd command
I recently made the switch and started using Debian Linux. How do I change directory in Linux using the cd command? How can I change a directory or folder in Linux?
You need to use the cd command to move from your present directory to another directory. You must have execute or search permission in the specified directory. This page shows basic examples of how to change directory in Linux using the cd command.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash with the terminal application |
Est. reading time | 2 minutes |
How to change directory in Linux
The procedure changes a directory or folder in Linux as follows:
- Let us change to your home directory in Linux, run: cd
- If you want to change to the /etc/security/ directory on Linux, execute: cd /etc/security/
- Want to go up one level of the directory tree in Linux? Try: cd ..
Let us see some examples and usage in details.
All examples tested with GNU/bash version 5.0.17 running on Ubuntu Linux 20.04 LTS desktop.
Changes the current directory in Linux
Let us change the current working directory to the home (login) directory in Linux, run:
cd
The default DIR is the value of the HOME shell variable. We can print that using the printf command/echo command as follows:
echo «$HOME»
To print the current working directory, use the pwd command:
pwd
Next change to an arbitrary directory named /etc/ufw/, type:
cd /etc/ufw
pwd
At this stage, you may want to list the directory contents. Hence, try the ls command:
ls
ls -l
Say you need to go down one level of the directory tree (say you want to change to the applications.d), run:
cd applications.d
pwd
ls -l
How do I go back to my home folder or directory in Linux?
Simply type any one of the following command:
cd
OR
cd
Changing to another directory in Linux using the cd command
How to change a folder in Linux
Get list of directories only in the current directory using the following:
ls -d */
Once you know the directory names, change it as per your needs:
cd linux
pwd
ls
To move back to a parent directory directory, type:
cd ..
Verify it:
pwd
ls
Linux change directory using the cd command
Linux change directory and symbolic links
One can force symbolic links to be followed. The syntax is:
cd -L dir1
cd -L link2
To use the physical directory structure without following symbolic links:
cd -P link2
Force symbolic links with the -L option and he physical directory structure with the -P option
Shell environment variables
- CDPATH : The search path for the cd command. It is a : separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string. We can set it as follows:
export CDPATH=/home/vivek/projects
## another example ##
export CDPATH=/home/vivek/projects:/nfs:/efs
Now go to /home/vivek/projects/aws, I can simply type
cd aws
Insetad of
cd /home/vivek/projects/aws/
# OR #
cd
/projects/aws/
A note about the autocd option
If set, a command name that is the name of a directory is executed as if it were the argument to the cd command. This option is only used by interactive shells. Turn it on:
shopt -s autocd
Now type directory or folder names such as bin in the $HOME and it will automatically convert to “cd $HOME/bin”:
bin
Another example:
Downloads
Autocorrect errors/typos of a folder name
Suppose cdspell is set to on , minor errors in the spelling of a directory component in a cd command will be corrected. For example:
Источник
Change directory to an external disk
I’ve two partitions on my windows OS and I’ve installed Ubuntu within windows.
Partition 1 : Windows and Linux OS
Partition 2 : Common storage files (called under the name New Volume)
I am looking at running a shell script that is placed in partition 2. I am able to run the shell when it is placed in the /home/. hierarchy of Ubuntu but I am unable to do so when it is placed in partition 2 which is being treated as an external disk by the OS.
I just want to know how can I actually change my working directory to a directory that is placed on an external disk which is mounted. What is the cd command to make the terminal look into a directory of the mounted disk?
2 Answers 2
I’m not quite sure what exactly is your problem, since you’re mentioning cd yourself, but just to confirm: to change a working directory in terminal, you use cd command:
External disks are usually mounted under /media, so to get to your disk, you can type
then press Tab , which will show you files and sub-directories in that directory. Type a few first letters of the sub-directory you need and press Tab again. When the full path is entered, press Enter . Easy.
To run a shell script from that disk, the easiest would be to use something like
Note that you’re invoking bash and passing it the name of the script, instead of running the script directly, like this:
the first version don’t need the executable bit to be set on the script file.
Источник