Directories and Files
Directories and Files
When you open a Linux system, you will see several default directories:
• Root Path: Represented by /, it is the starting point of the file system. All other
directories are within this path.
• Home Directory: Located at /home/username, it is a special place for you to store
your files.
• Absolute Path: Starts from the root directory and provides the complete location of a
file or directory. Example:
/home/username/documents/file.txt
• Relative Path: Starts from your current directory. If you are in your home directory,
you can refer to the documents folder as:
documents/file.txt
4. Navigating Directories
You can use the cd command (which stands for "change directory") to navigate through
directories. Here are various commands for navigating:
bash
Copy code
cd ~
bash
Copy code
cd /
bash
Copy code
cd -
bash
Copy code
cd ..
bash
Copy code
cd ../..
bash
Copy code
cd ../../..
bash
Copy code
cd /home/username/documents
Creating a Directory: Use the mkdir command followed by the directory name.
bash
Copy code
mkdir new_directory
Deleting a Directory: Use the rmdir command followed by the directory name to delete an
empty directory.
bash
Copy code
rmdir new_directory
If the directory is not empty and you want to delete it along with all its contents, you can use
the rm command:
The -r option stands for "recursive," which means it will delete the directory and
everything inside it.
bash
Copy code
rm -rf directory_name
The -f option stands for "force," and it will ignore non-existent files and never
prompt for confirmation.
Renaming a Directory: Use the mv command followed by the old directory name and the
new directory name.
bash
Copy code
mv old_directory new_directory
You can create files using several methods. Here’s how to use the cat command:
bash
Copy code
cat > myfile.txt
Viewing File Contents: To see the contents of a file, use the cat command:
bash
Copy code
cat myfile.txt
Appending Text to a File: To add more text to an existing file without deleting the old
content, use the >> operator:
bash
Copy code
echo "This is additional text." >> myfile.txt
Adding More Lines Using cat: You can append to a file using the cat command as well:
bash
Copy code
cat >> myfile.txt
Open a File with vim: You can create a new file or open an existing one:
bash
Copy code
vim myfile.txt
1. Insert Mode: Press i to enter insert mode, allowing you to type and edit the file.
2. Save Changes: After editing, press ESC to exit insert mode, then type :w and press
Enter to save.
3. Exit vim: Type :q and press Enter to quit. To save and exit at the same time, use
:wq.
4. Force Quit: If you want to exit without saving changes, type :q! and press Enter.
8. Summary
Now you know about Linux directories, paths, and how to manage files! Here’s a quick
recap:
Practice Exercises