File and Directory Operations (ls, cd, mkdir, rm)
Category: Linux Command Basics
Type: Linux Commands
Generated on: 2025-07-10 03:05:00
For: System Administration, Development & Technical Interviews
File and Directory Operations Cheatsheet (Linux Commands)
Section titled “File and Directory Operations Cheatsheet (Linux Commands)”This cheatsheet covers fundamental file and directory manipulation commands in Linux: ls, cd, mkdir, and rm. It’s designed for both beginners and experienced users, offering practical examples and advanced techniques.
1. Command Overview
ls(List Directory Contents): Displays files and directories within a specified location. Crucial for navigating and understanding the file system.cd(Change Directory): Navigates the file system, moving between directories. Essential for getting around.mkdir(Make Directory): Creates new directories. Fundamental for organizing files and projects.rm(Remove File or Directory): Deletes files and directories. Use with EXTREME caution!
2. Basic Syntax
ls [options] [file or directory]cd [directory]mkdir [options] directoryrm [options] file or directory
3. Practical Examples
-
ls: List files and directories in the current directory.Terminal window lsfile1.txt directory1 file2.txt -
ls -l: List files with detailed information (permissions, size, owner, modification date).Terminal window ls -l-rw-r--r-- 1 user user 1024 Jan 1 10:00 file1.txtdrwxr-xr-x 2 user user 4096 Jan 1 10:05 directory1-rw-r--r-- 1 user user 2048 Jan 1 10:10 file2.txt -
cd directory1: Change directory todirectory1.Terminal window cd directory1pwd #verify the change/home/user/directory1 -
cd ..: Go up one directory level (to the parent directory).Terminal window cd ..pwd/home/user -
cd ~: Go to the user’s home directory.Terminal window cd ~pwd/home/user -
mkdir new_directory: Create a new directory namednew_directory.Terminal window mkdir new_directorylsfile1.txt directory1 file2.txt new_directory -
rm file1.txt: Delete the filefile1.txt. WARNING: This is permanent!Terminal window rm file1.txtlsdirectory1 file2.txt new_directory -
rm -r directory1: Delete the directorydirectory1and its contents recursively. WARNING: This is permanent and can delete entire directory trees! Use with extreme caution!Terminal window rm -r directory1lsfile2.txt new_directory
4. Common Options
| Command | Option | Description | Example |
|---|---|---|---|
ls | -l | Long listing format (detailed information). | ls -l |
ls | -a | Show all files, including hidden files (files starting with .). | ls -a |
ls | -h | Human-readable file sizes (e.g., 1K, 234M, 2G). Often used with -l. | ls -lh |
ls | -t | Sort by modification time (newest first). | ls -lt |
ls | -r | Reverse the order of the listing (e.g., oldest first when used with -t). | ls -ltr |
ls | -d | List directories themselves, not their contents. | ls -ld directory1 |
ls | -R | Recursively list subdirectories encountered. | ls -R |
ls | --color | Colorizes the output. Often aliased in .bashrc or .zshrc. | ls --color=auto |
cd | - | Go to the previous directory. | cd - |
mkdir | -p | Create parent directories as needed. Useful for creating nested directory structures. | mkdir -p path/to/new/directory |
mkdir | -m MODE | Set the permissions for the new directory to MODE. MODE is an octal number representing the permissions. | mkdir -m 755 new_directory |
rm | -r or -R | Recursively remove directories and their contents. EXTREMELY DANGEROUS! | rm -r directory1 |
rm | -f | Force removal (ignore nonexistent files, never prompt). Useful in scripts. | rm -f file1.txt |
rm | -i | Interactive mode (prompt before each removal). A good safety measure. | rm -i file1.txt |
rm | -v | Verbose mode (show what is being removed). | rm -v file1.txt |
5. Advanced Usage
-
Combining
lswithgrep: Find files containing specific text in their name.Terminal window ls -l | grep "pattern"Example: Find all files ending with
.log:Terminal window ls -l | grep "\.log$" -
Using
findwithrmfor complex file removal: Find and delete files based on various criteria (age, size, name). This is very powerful but requires careful consideration.Terminal window find . -name "*.tmp" -mtime +7 -deleteThis command finds all files ending in
.tmpthat are older than 7 days and deletes them. Double-check thefindcommand output before adding-delete! Consider using-print0andxargs -0for filenames with spaces or special characters.Terminal window find . -name "*.tmp" -mtime +7 -print0 | xargs -0 rm -f -
Creating multiple directories with
mkdir -p:Terminal window mkdir -p project/src/main/javaThis creates the entire directory structure
project/src/main/javaif it doesn’t already exist. -
Using
cdwith environment variables:Terminal window cd $HOME/projects # Go to the 'projects' directory within your home directory. -
Listing files by size:
Terminal window ls -lS # Sort by size, largest firstls -lSr # Sort by size, smallest first
6. Tips & Tricks
-
Tab Completion: Use the Tab key to auto-complete file and directory names. This saves typing and reduces errors. Type the beginning of a name and press Tab. If there’s only one match, it will complete. If there are multiple matches, press Tab twice to see a list of possibilities.
-
History: Use the up and down arrow keys to navigate through your command history.
-
Aliases: Define aliases in your
.bashrcor.zshrcto create shortcuts for frequently used commands. For example:Terminal window alias ll='ls -l'alias la='ls -la'alias rm='rm -i' # Make rm interactive by defaultAfter adding these aliases, run
source ~/.bashrcorsource ~/.zshrcto activate them. -
pushdandpopd: These commands allow you to navigate between directories and maintain a directory stack.pushd <directory>changes to the specified directory and adds the previous directory to the stack.popdreturns to the last directory pushed onto the stack.Terminal window pushd /var/log #Change to /var/log and save the current directorypwd/var/logTerminal window pushd /tmp #Change to /tmp and save the current directorypwd/tmpTerminal window popd #Go back to /var/logpwd/var/logTerminal window popd #Go back to the original directorypwd/home/user -
Globbing (Wildcards): Use wildcards to match multiple files.
*: Matches any character(s).rm *.txtdeletes all files ending in.txt.?: Matches any single character.ls file?.txtlists files likefile1.txt,file2.txt, etc.[]: Matches any character within the brackets.ls file[1-5].txtlists files likefile1.txt,file2.txt, …,file5.txt.
7. Troubleshooting
- “Permission denied”: You don’t have the necessary permissions to access or modify the file or directory. Use
ls -lto check permissions andsudoif necessary (and if you have sudo privileges), but be careful withsudo rm. Consider usingchownorchmodto change file ownership or permissions. - “No such file or directory”: The file or directory you specified doesn’t exist. Double-check the spelling and path. Use
pwdto confirm your current location. rm: cannot remove 'directory': Is a directory: You need to userm -rto remove a directory and its contents. Be extra cautious!- Accidental
rm -rf /: This is a classic mistake that can wipe out your entire system. Be extremely careful when usingrm -rfand ALWAYS double-check the path you are deleting! Consider using a tool likesafe-rmto prevent accidental deletion of important files. - Hidden files not showing up: Use
ls -ato display hidden files (files starting with a dot).
8. Related Commands
pwd(Print Working Directory): Displays the current directory.cp(Copy): Copies files and directories.mv(Move/Rename): Moves or renames files and directories.touch(Create Empty File or Update Timestamp): Creates an empty file or updates the access and modification times of an existing file.chmod(Change Permissions): Modifies file permissions.chown(Change Owner): Modifies file ownership.file(Determine File Type): Determines the type of a file.tree(Visualize Directory Structure): Displays a tree-like representation of a directory structure. (Requires installation).locateandfind(Search for Files): Powerful tools for finding files based on various criteria.
This cheatsheet provides a solid foundation for working with files and directories in Linux. Remember to practice these commands and experiment with different options to become proficient. Always exercise caution when using potentially destructive commands like rm.