File Operations in Linux
Overview
Managing files is one of the most common tasks in Linux! Whether you're creating documents, organizing directories, or cleaning up old files, these commands are essential to your daily workflow.
Key Commands
Creating Files
touch filename.txt
Creates an empty file. If the file already exists, it updates the timestamp.
Examples:
You can create multiple files at once!
touch notes.txttouch file1.txt file2.txt file3.txtYou can create multiple files at once!
Copying Files
cp source.txt destination.txt
Copies a file from one location to another.
Options:
-r- Copy directories recursively-i- Interactive mode (asks before overwriting)-v- Verbose (shows what's being copied)
Examples:
Use -r to copy entire directories
cp document.txt backup.txtcp -r folder1/ folder2/Use -r to copy entire directories
Moving/Renaming Files
mv oldname.txt newname.txt
Moves or renames files and directories. Moving to the same directory = renaming!
Examples:
No -r needed - mv works on directories too!
mv old.txt new.txt (rename)mv file.txt /home/user/Documents/ (move)No -r needed - mv works on directories too!
Deleting Files
rm filename.txt
Removes (deletes) files. This is permanent - no trash bin!
Options:
-r- Remove directories and their contents-f- Force removal without prompting-i- Interactive (asks for confirmation)
Examples:
Always be careful with rm!
rm oldfile.txtrm -r oldfolder/rm -i important.txtAlways be careful with rm!
Creating Directories
mkdir directoryname
Creates a new directory (folder).
Options:
-p- Creates parent directories as needed
Examples:
-p creates the whole path at once
mkdir Projectsmkdir -p Documents/Work/Reports-p creates the whole path at once
Removing Directories
rmdir directoryname
Removes an empty directory. Use rm -r for directories with content.
Important Safety Tips
- No undo! Deleted files don't go to a trash bin - they're gone
- Use -i flag: Add -i to rm or cp for confirmation prompts
- Double-check paths: Make sure you're in the right directory
- Avoid wildcards with rm: Be very careful with
rm * - Test with ls first: Use
lsto see what would be affected