Working on an Ubuntu server, you often need to reorganize directory structures. A common task is moving all contents (files and subdirectories) from a nested folder to its parent directory.
Given the following structure where you're currently in
/folder1
:/folder1/ ├── file1.txt └── folder2/ ├── file2.txt ├── file3.log └── subfolder/ └── file4.csvTo move everything from
folder2
tofolder1
, use:mv folder2/* .For recursive movement including hidden files:
mv folder2/{.,}* . 2>/dev/null || :Case 1: When folder2 contains subdirectories
mv folder2/* ./ mv folder2/.* ./ 2>/dev/null || trueCase 2: Using find command for complex scenarios
find folder2 -mindepth 1 -exec mv -t . {} +
- Forgetting the dot (.) as destination
- Not handling hidden files
- Moving the parent folder itself accidentally
For large directory trees or remote operations:
rsync -a folder2/ . rm -rf folder2
When organizing files on a Linux server, you might encounter situations where you need to flatten your directory structure. A typical case is when you want to move all contents (including files and subdirectories) from a nested folder up one level to its parent directory.
The Linux
mv
command, combined with proper wildcards, can accomplish this task efficiently. Here's the basic syntax:mv /folder1/folder2/* /folder1/
The above command won't move hidden files (those starting with a dot). To include them:
mv /folder1/folder2/{*,.*} /folder1/ 2>/dev/null || true
While the previous commands move files, they don't properly handle nested subdirectories. For complete recursive movement:
mv /folder1/folder2/* /folder1/folder2/.* /folder1/ 2>/dev/null || true rmdir /folder1/folder2
Let's break down a practical scenario where you're in
folder1
and want to move everything fromfolder2
:# Current directory structure $ pwd /folder1 $ ls folder2 file1.txt file2.jpg subfolder .hiddenfile # Move all contents $ mv folder2/* folder2/.* ./ 2>/dev/null || true # Verify folder2 is empty $ rmdir folder2
For more complex scenarios where you need selective movement,
find
can be more precise:find folder2/ -mindepth 1 -exec mv -t ./ {} +
Be cautious when:
- Moving large numbers of files (consider using
rsync
for better progress tracking) - Dealing with files that might overwrite existing ones in the destination
- Handling special characters in filenames