File and directory management is one of the most essential skills when using Unix. Whether you’re creating, moving, copying, or deleting files, Unix provides straightforward commands to help you organize your data efficiently.
In this blog, we’ll cover the most common file and directory management tasks with simple examples.
1. Creating Files and Directories
Create an Empty File: touch
The touch
command creates an empty file.
Example:
$ touch myfile.txt
Now, a file named myfile.txt
exists in your current directory.
Create a Directory: mkdir
The mkdir
command creates a new directory.
Example:
$ mkdir myfolder
This creates a directory named myfolder
in your current location.
2. Viewing File Contents
See the Contents of a File: cat
The cat
command displays the entire content of a file.
Example:
$ cat myfile.txt
View Large Files: less
For long files, use less
to scroll through the content one page at a time.
Example:
$ less largefile.txt
3. Copying and Moving Files
Copy Files: cp
The cp
command makes a copy of a file or directory.
Examples:
- Copy a file:
$ cp myfile.txt backup.txt
- Copy a directory (use the
-r
option for recursive copying):
$ cp -r myfolder backup_folder
Move or Rename Files: mv
The mv
command moves or renames files and directories.
Examples:
- Move a file to another directory:
$ mv myfile.txt myfolder/
- Rename a file:
$ mv myfile.txt newname.txt
4. Deleting Files and Directories
Delete Files: rm
The rm
command removes files.
Example:
$ rm myfile.txt
Delete Directories: rm -r
Use the -r
option to delete directories and their contents.
Example:
$ rm -r myfolder
Be careful: The rm
command permanently deletes files without moving them to a trash bin.
5. Organizing Files
Move Multiple Files with Wildcards
Wildcards like *
let you work with multiple files at once.
Example:
- Move all
.txt
files into a directory:
$ mv *.txt myfolder/
Sort Files by Time or Size
Use ls
with options to organize your view:
- Sort by time:
$ ls -lt
- Sort by size:
$ ls -lS
6. Checking Disk Space
See File Sizes: du
The du
(Disk Usage) command shows the size of files and directories.
Example:
$ du -sh myfolder
This shows the total size of myfolder
.
Check Free Space: df
The df
command shows how much disk space is available.
Example:
$ df -h
The -h
option makes the output human-readable (e.g., in MB or GB).
Practice Time!
- Create a new directory and a file inside it:
$ mkdir project
$ touch project/notes.txt
- Copy the file to a new location:
$ cp project/notes.txt notes_backup.txt
- Delete the original file:
$ rm project/notes.txt
Summary
- Use
touch
andmkdir
to create files and directories. - Use
cp
andmv
to copy or move files. - Use
rm
to delete files and directories carefully.