Managing Files and Directories (cp, mv, rm, mkdir, rmdir)
Here's a quick guide to managing files and directories using common Linux commands like cp, mv, rm, mkdir, and rmdir, with examples and outputs.
1. cp (Copy Files and Directories)
- Syntax:
cp [options] source destination
- Description: Copies files or directories from one location to another.
Example:
$ cp file1.txt file2.txt
Explanation: Copies the contents of file1.txt into file2.txt. If file2.txt does not exist, it will be created.
Output:
$ ls
file1.txt file2.txt
2. mv (Move/Rename Files and Directories)
- Syntax:
mv [options] source destination
- Description: Moves or renames files and directories.
Example:
$ mv file2.txt newfile.txt
Explanation: Renames file2.txt to newfile.txt.
Output:
$ ls
file1.txt newfile.txt
3. rm (Remove Files and Directories)
- Syntax:
rm [options] file(s)
- Description: Deletes files or directories.
Example:
$ rm newfile.txt
Explanation: Deletes the newfile.txt.
Output:
$ ls
file1.txt
Note: Use rm -r to remove directories and their contents recursively.
Example:
$ rm -r directory_name
Explanation: Deletes the directory directory_name and all its contents.
4. mkdir (Make Directories)
- Syntax:
mkdir [options] directory_name
- Description: Creates a new directory.
Example:
$ mkdir new_directory
Explanation: Creates a directory named new_directory.
Output:
$ ls
file1.txt new_directory
5. rmdir (Remove Directories)
- Syntax:
rmdir [options] directory_name
- Description: Removes an empty directory.
Example:
$ rmdir new_directory
Explanation: Deletes the new_directory (only if it's empty).
Output:
$ ls
file1.txt
Note: If the directory is not empty, rmdir will not delete it. Use rm -r to delete a directory with contents.
Summary
cp copies files and directories.
mv moves or renames them.
rm deletes them.
mkdir creates directories.
rmdir removes empty directories.
These commands are fundamental for managing files and directories in Linux-based systems.