Move dir in linux

Linux command to move a directory

This is a perfectly good question that belongs on StackOverflow. Granted, it is a naive mistake — but that’s what SO is for; it helps people overcome naivety by allowing them to ask questions and learn from answers. See SO Blog and Podcast #53 (Joel says no question is too simple for Stack Overflow. ).

5 Answers 5

You should use mv -if old/* new/ without the trailing * .

This is because it unrolled to

mv -if old/foo old/bar old/baz new/foo new/bar new/baz 

i.e. move everything into new/baz

This is not what you wanted.

reef@localhost:/tmp/experiment$ ls a 11 22 33 reef@localhost:/tmp/experiment$ ls b 22 33 reef@localhost:/tmp/experiment$ ls a b reef@localhost:/tmp/experiment$ mv a/* b reef@localhost:/tmp/experiment$ ls a reef@localhost:/tmp/experiment$ ls b 11 22 33 

It works. What are You trying to achieve? Could You please write a short example of what the input data should look like and what the output data should look like? The truth is I have no idea what You are trying to do 🙂 Help me help You.

note that mv a/* b/ don’t move files .* (file name start with ‘.’) in a/ to b/

$ mkdir -p a/d b && touch a/f a/.f a/d/.f $ mv a/* b/ $ ls -a a/ . .. .f 

If you are copying from an ext2/3/4 file system to a FAT32 file system, and a filename has an invalid character for FAT32 naming conventions, you get this terribly annoying and incorrect as hell error message. How do I know? I wrestled with this bug — yes, it’s a KERNEL BUG — for 6 hours before it dawned on me. I thought it was a shell interpreter error, I thought it was an «mv» error — I tried multiple different shells, everything. Try this experiment: on an ext file system, «touch ‘a:b'» them «mv» it to a FAT32 file system. Try it, you’ll enjoy (hate) the results. The same is true for » (\074 and \076).

Thanks for «man mv» — that’s a real big help, don’t quit your day job.

Might be you got the answer but above answer is not working for me. and finally lots of researching I got the answer. (Issue is due to files-ownership)
and just put sudo before the command and its working. 🙂 Same thing for cp and mv command.

Читайте также:  Pro tools on linux

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to move a directory in Linux

In Linux we can move the directories to a specific folder and protect them by changing their access permission in order to secure the files and data present in those directories. To move the directory from one path to another is much simpler and can be done easily.

The one thing most people are confused about is the difference between move and copy command; copy command is used to make the clone of files/directories to some other paths while keeping the original file/directory at its original path, while the move command is used to move the file/directory from its original path and place it to some other path.

In this write-up, we have explained the methods in detail through which we can move the directories from one path to another in Linux.

How to move directory in Linux

There are two methods to move directories from one destination to another in Linux is either by command line method or graphical user interface, both are discussed in detail.

Method 1: Command line method

We have two directories with the name, mydirectory1, and mydirectory2, we can list both of them using the ls command:

The general syntax of moving the directory from one path to another is:

Use the mv command to move the directory from source to some destination and we can use some options along with this command. The options which can be used with the mv command are:

Options Description
-f It will overwrite the functions forcibly while moving the directory from source to destination
-i It will enable the interactive mode
-v It will show you the progress of the command execution
-u It will update the destination files
-z It will set the security context of the file to the default settings
-n It will disable the overwriting in the destination files

To understand this, we will move the directory mydirectory2 from /home/hammad (current working directory) to /home/hammad/Documents using the command:

We have used the “-f” option in the above command which is used to forcibly move the directories, and list down the contents, using the ls command:

Читайте также:  Mxl чем открыть в linux

Only “mydirectory1” is present which means the “mydirectory2” has successfully been moved into to Documents directory, to verify it, use the command:

Similarly, we can move multiple directories using the command:

$ mv -vfi / home / hammad / Documents / mydirectory1 / home / hammad / Documents / mydirectory2 / home / hammad

In the above-executed command, we have moved the multiple directories; mydirectory1 and mydirectory2, from /home/hammad/Documents to /home/hammad using the flags “-vfi” where “v” is used to display the progress of executed command, “f” is used to forcibly moved the directory if required, and “i” is used to enabling the interactive mode.

Method 2: Graphical User interface

For the GUI method, go to the destination folder, right-click on the directory you want to move, and choose the move option:

Choose the “Destination folder” in our case, it is Documents, and then clicks on the “Select” button:

The directory has successfully been moved, open the “Documents” directory to verify the mobility of the mydirectory2 from /home/hammad to /home/hammad/Documents:

Conclusion

The directory can be moved either by using the command line method or GUI method; both are convenient and understandable, it’s up to the reader’s choice. In this write-up, we have explained both the methods in detail, the command line method is recommended because with this method you can use other options using the flags.

About the author

Hammad Zahid

I’m an Engineering graduate and my passion for IT has brought me to Linux. Now here I’m learning and sharing my knowledge with the world.

Источник

Команда mv

Команда mv Linux

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

Синтаксис

исходные_файлы — это то, что мы будем перемещать или переименовывать. То есть это либо один файл, либо несколько файлов, либо директория, либо несколько директорий.

куда — это название директории, в которую мы перемещаем исходные файлы или директории. Или же это новое название файла или директории, если выполняется переименование. То есть это либо директория, либо новое название файла или директории.

  • Переместить один или несколько файлов в другую директорию.
  • Переместить одну или несколько директорий в другую директорию.
  • Переименовать файл.
  • Переименовать директорию.

Опции

Создать резервную копию существующих файлов, которые будут перезаписаны или удалены.
Имя для резервной копии может создаваться по определенным правилам. Для этого используется опция —backup=МЕТОД В качестве значения МЕТОД можно указать:

  • none или off — не делать резервных копий, даже если включена опция —backup
  • numbered или t — имя резервной копии получит числовой индекс (пример: myfile.txt~2~ ).
  • existing или nil — если в директории уже есть резервные копии с числовыми индексами, то использовать числовые индексы для новых резервных копий, во всех остальных случаях использовать метод simple .
  • simple или never — делать обычные резервные копии (пример: myfile.txt~ ).
Читайте также:  Поддержка ssd в linux

Изменить символ суффикса, который добавляется к именам резервных копий (при использовании опции —backup ). По умолчанию СУФФИКС равен значку тильды ~

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

Примеры использования команды mv

Рассмотрим несколько примеров использования команды mv в Linux.

Рекомендуется всегда использовать опцию -v , чтобы получать информацию о том, что именно команда mv делает с файлами.

Также крайне рекомендуется использовать опцию -i , чтобы выдавался запрос на перезапись существующих файлов. В примерах ниже мы эти опции опускаем.

Переместить файл

Переместим файл myfile1.txt в директорию mydir/ (директория должна существовать). Для этого выполняем команду без каких-либо аргументов:

Переименовать файл

Переименуем файл myfile1.txt в myfile2.txt :

Переименовать директорию

Переименуем директорию mydir1 в mydir2 . Выполняется точно также, как и переименование файлов.

Создавать резервные копии существующих файлов

Предположим, что нам нужно переименовать файл myfile1.txt в myfile2.txt , но файл myfile2.txt уже существует. Можно воспользоваться опцией -b , чтобы создать резервную копию существующего файла:

mv -b myfile1.txt myfile2.txt

В результате сначала существующий файл myfile2.txt будет переименован в myfile2.txt~ , то есть будет создана его резервная копия, и только потом файл myfile1.txt будет переименован в myfile2.txt .

Вместо значка тильда ~ можно добавлять к именам резервных копий произвольный суффикс. Например, добавим суффикс .bak . Для этого воспользуемся опцией -S

mv -b -S ".bak" myfile1.txt myfile2.txt

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

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

Переместим сразу три файла в директорию mydir/

mv myfile1 myfile2 myfile3 mydir/

Переместим все файлы из текущей директории в директорию mydir/

Переместим все файлы с расширением .jpg в директорию mydir/

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

Предположим, что нам нужно переместить все файлы из одной директории в другую, но если в директории назначения уже есть файлы с такими же именами, то их не перемещать. Для этого используем опцию -n

Переместить только те файлы, которые новее

Предположим, что нам нужно переместить все файлы из одной директории в другую, но если в другой директории уже есть файлы с такими же именами, то заменять существующие файлы только если исходный файл новее (по дате). Для этого используем опцию -u

Если в имени файла есть пробелы

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

Предположим, что нам нужно переименовать файл в имени которого содержится пробел — My file1.txt . Для этого можно заключить имя файла в кавычки (для файла назначения аналогично).

mv "My file1.txt" "My file2.txt"

Или использовать символ косой черты перед пробелом.

mv My\ file1.txt My\ file2.txt

Источник

Оцените статью
Adblock
detector