How to move directory linux

How To: Linux / Unix Move Directory Up One Level

I would like to move a directory one level up into the root directory. I have all my html files located in /home/apache2/www/html directory, and I would like to move /home/apache2/www/html to one level up at /home/apache2/www/. How can I accomplish this over the ssh session?

You need to use the mv command that moves one or more files or directories from one place to another. You must have have write permission for the directories which the file will move between. The syntax is as follows to move /home/apache2/www/html directory up one level at /home/apache2/www/ directory.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix CLI
Est. reading time 1m

Linux / Unix Move Directory Up One Level with the mv Command

Open a command-line terminal (select Applications > Accessories > Terminal), and then type (for remote system use ssh for login):
$ mv /home/apache2/www/html/ /home/apache2/www/
OR
$ mv /home/apache2/www/html/ ..
Please note that Unix / Linux uses the special name .. to refer to the parent directory of a particular directory.

Linux / Unix Move Directory Up One Level Examples

In this example move /usb/archives/data/ directory to up one level using the mv command as follows:
$ cd /usb/archives/data/
$ mv -v data/ ..
Sample outputs:

Fig.01: mv Unix / Linux Command

  • 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

  • -v : Cause mv to be verbose, showing files after they are moved.

How Do I Move Multiple Directories Up One Level?

The syntax is as follows to moves each file named by a source operand to a destination file in the existing directory named by the directory operand:
$ mv dir1 dir2 ..
In this example move both /home/vivek/projects/foo/ /home/vivek/projects/bar/ directories up one level:
$ mv /home/vivek/projects/foo /home/vivek/projects/bar ..
Now both bar and foo moved to the /home/vivek/projects/ directory. You can move files using the same syntax. In this example move movie-cd1.avi movie-cd2.avi files up one level:
$ mv /home/vivek/Downloads/movie-cd1.avi /home/vivek/Downloads/movie-cd2.avi ..

How Do I Move All Directories Up One Level?

Use the following syntax to move all directories and files in /home/vivek/data/sales/ to /home/vivek/data/:
$ mv -v /home/vivek/data/sales/ ..
OR
$ cd /home/vivek/data/sales/
$ mv -v sales/ ..

How Do I Move All *.pl or *.c Files Up One Level?

Use the following syntax to move all *.pl (perl files) or *.c (C program files) up one level:
$ mv -v /home/vivek/projects/*.pl ..
$ mv -v /home/vivek/projects/*.c ..

Conclusion

You just learned how to move directory directory up one level using the mv command. For more info read the mv command man page by typing the following man command:
$ man mv

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как переместить файлы и каталоги в Linux (mv Command)

How to Move Files and Directories in Linux (mv Command)

В этом руководстве мы объясним, как использовать mv команду для перемещения файлов и каталогов.

Перемещение файлов и каталогов является одной из самых основных задач, которые вам часто приходится выполнять в системе Linux.

Как использовать mv команду

Команда mv (короткая от перемещения) используется для переименования и перемещения файлов и каталогов из одного места в другое. Синтаксис mv команды следующий:

Это SOURCE может быть один или несколько файлов или каталогов, и DESTINATION может быть один файл или каталог.

  • Когда несколько файлов или каталогов задаются как SOURCE , DESTINATION каталог должен быть. В этом случае SOURCE файлы перемещаются в целевой каталог.
  • Если вы указываете один файл как SOURCE , а DESTINATION целью является существующий каталог, то файл перемещается в указанный каталог.
  • Если вы указываете один файл как SOURCE и один файл как DESTINATION цель, вы переименовываете файл .
  • Когда SOURCE каталог является каталогом и DESTINATION не существует, SOURCE он будет переименован в DESTINATION . В противном случае, если он DESTINATION существует, он будет перемещен в DESTINATION каталог.

Чтобы переместить файл или каталог, вам необходимо иметь права на запись как для, так SOURCE и для DESTINATION . В противном случае вы получите ошибку «Отказано в разрешении».

Например, чтобы переместить файл file1 из текущего рабочего каталога в /tmp каталог, который вы запустите:

Чтобы переименовать файл, вам нужно указать имя файла назначения:

Синтаксис для перемещения каталогов такой же, как при перемещении файлов. В следующем примере, если dir2 каталог существует, команда переместится dir1 внутрь dir2 . Если dir2 не существует, dir1 будет переименован в dir2 :

Перемещение нескольких файлов и каталогов

Чтобы переместить несколько файлов и каталогов, укажите файлы, которые вы хотите переместить, в качестве источника. Например, для перемещения файлов file1 и file2 в dir1 каталоге вы должны ввести:

Команда mv также позволяет использовать сопоставление с образцом. Например, чтобы переместить все pdf файлы из текущего каталога в

/Documents каталог, вы должны использовать:

mv Параметры команды

Команда mv принимает несколько параметров, которые влияют на поведение команды по умолчанию.

В некоторых дистрибутивах Linux, mv может быть псевдоним к mv команде с пользовательским набором опций. Например, в CentOS mv есть псевдоним mv -i . Вы можете узнать, mv является ли псевдоним, используя type команду:

Если mv это псевдоним, вывод будет выглядеть примерно так:

Если указаны конфликтующие параметры, последний имеет приоритет.

Подскажите перед перезаписью

По умолчанию, если целевой файл существует, он будет перезаписан. Чтобы запросить подтверждение, используйте -i опцию:

Перезаписать тип файла y или Y .

Перезапись силы

Если вы попытаетесь перезаписать файл, доступный только для чтения, mv команда предложит вам перезаписать файл:

Чтобы избежать запроса, используйте -f параметры:

Эта опция особенно полезна, когда вам нужно перезаписать несколько файлов только для чтения.

Не перезаписывать существующие файлы

-n Вариант не говорит и mv не перезаписать существующий файл:

Если file1 существует, команда выше ничего не сделает. В противном случае он переместит файл в /tmp каталог.

Резервное копирование файлов

Если целевой файл существует, вы можете создать его резервную копию с помощью -b опции:

Файл резервной копии будет иметь то же имя, что и исходный файл, к которому будет

добавлена функция тильды ( ).

Используйте команду ls, чтобы убедиться, что резервная копия была создана:

Подробный вывод

Еще одна полезная опция -v . Когда эта опция используется, команда печатает имя каждого перемещенного файла:

Вывод

Команда mv используется для перемещения и переименования файлов и каталогов.

Для получения дополнительной информации о mv команде проверьте страницу руководства или введите man mv свой терминал.

Новые пользователи Linux, которых пугает командная строка, могут использовать файловый менеджер GUI для перемещения своих файлов.

Источник

How to Move Directories in Linux

Home » SysAdmin » How to Move Directories in Linux

Managing files and directories is one of the most basic tasks when working in a Linux system. You can move directories in Linux using the GUI and system commands.

In this tutorial, we will cover the two methods you can use to move directories in Linux.

  • A system running a Linux distribution
  • An account with sudo privileges
  • Access to the terminal window/command line

How to Use mv Command to Move Directories in Linux

The mv command is a Linux system utility that allows you to move files and directories from one place to another. It uses the following command syntax:

For instance, to move the Example directory to the Downloads directory use:

There will be no output if the command has been successful.

Moving multiple directories works by changing the syntax to include multiple sources:

For example, to move the Example1, Example2, and Example3 directories to the Downloads directory use:

Note: Learn how to create new directories in Linux using the terminal in our guide to the Linux mkdir command.

The mv command is also used to rename files and directories with the following syntax:

For example, renaming the Example file into Test:

Note: If the destination directory does not exist, the mv command will automatically rename the source directory to the destination name.

mv Command Options

The mv command uses the following options:

  • —backup : Creates a backup of the destination file. Allows you to pass additional arguments to change how the command behaves.
  • -b : Works like —backup but does not accept arguments.
  • -f : Automatically overwrite destination files.
  • -i : Enables interactive mode, with a prompt asking for input before overwriting files.
  • -n : Disables overwriting destination files.
  • —strip-trailing-slashes : Removes trailing slashes («/») from source file or directory names.
  • -S : Provide a new suffix for the backup files.
  • -t : Move all provided sources into a destination directory.
  • -T : Treat the provided destination as a file instead of a directory.
  • -u : Update destination files.
  • -v : Show command output in verbose format.
  • -Z : Set the destination file security context to default.

If the destination file already exists, using the -b option allows you to create a backup of the existing file:

In this example, the mv command creates a backup of the existing test.txt file in the Example directory before overwriting. The backup file has the same name as the original, with a tilde («

«) added to the end. Use the ls command to verify the backup file:

Change the default suffix for backup files (tilde) by combining the —backup and -S options. The new suffix is passed as an argument after the -S option and before specifying the source and destination files or directories:

In this example, the new backup filename suffix is 01 :

Using the -i option prompts the user to confirm overwriting existing files. Typing Y or N and pressing Enter confirms or cancels overwriting, respectively:

The -f option automatically overwrites any existing files in the destination directory, while the -n option disables overwriting and skips existing files. Using the -u option only overwrites the file if the source file is newer than the destination file of the same name.

Have the mv command output show the step-by-step process of moving files and directories by using the -v option:

How to Move Directories Using GUI in Linux

There are two methods of moving directories in Linux using the GUI.

Option 1: Copy and Paste

1. Select the directory you want to move and press Ctrl+X. Alternatively, right-click the directory and select Cut from the drop-down menu.

2. Navigate to the destination and press Ctrl+V or right-click the empty space and select Paste from the drop-down menu to move the directory.

Option 2: Move To. Option

1. Another method is to right-click the directory and select Move to… from the drop-down menu.

2. In the Select Move Destination window, navigate to the destination and click Select to move the directory.

Note: If you are using Ubuntu, check out our tutorial on how to install a GUI on Ubuntu.

After reading this article, you should know how to move directories in Linux using the GUI and the built-in mv command.

Learn more about using Linux commands in our Linux Commands Cheat Sheet.

For more information about Linux directories, make sure to read our article how to rename a directory in Linux.

Источник

Читайте также:  Как увеличить герцовку монитора windows 10 intel
Оцените статью