π§ ls Command Mastery in Linux β
Welcome to your deep dive into the ls command β one of the most fundamental tools for navigating Linux. This guide follows a Socratic learning style with prompts, outputs, and practical challenges.
π£ Getting Started with ls β
Task
What do you think ls does when run without any options? Try it:
lsAnswer
Lists files and directories in the current working directory.
TIP
The default behavior does not show hidden files.
π Listing with More Detail β
ls -lOutput
-rw-r--r-- 1 user group 1234 Jun 5 09:00 report.txt
drwxr-xr-x 2 user group 4096 Jun 5 09:01 projectsTask
Can you guess what each of the columns represent?
Answer
Permissions, links, owner, group, size, date, filename
π Show Hidden Files β
ls -aOutput
. .. .bashrc .gitconfig notes.txtPitfall
., .., and .* files are hidden by default.
π Combine Flags β
ls -laTIP
Combining -l and -a gives you long listing including hidden files.
β± Sort by Time β
ls -ltOutput
-rw-r--r-- 1 user group 4096 Jun 6 11:11 today.txt
-rw-r--r-- 1 user group 1234 May 29 08:45 old.txtTask
Can you guess what ls -ltr does?
Answer
Sorts by modification time in reverse order.
π Filter with Patterns β
ls *.txtTask
Predict the output if your folder has these files: notes.txt, image.png, todo.txt, README.md
Answer
notes.txt todo.txtπ Colored Output β
ls --color=autoTIP
Color helps differentiate between files, directories, executables, etc.
π¦ File Sizes with -lh β
ls -lhOutput
-rw-r--r-- 1 user group 1.2K Jun 6 09:15 example.txtTIP
-h makes file sizes human-readable (K, M, G).
π― Practice Challenge 1 β
Task
List all files in /var/log that are larger than 1 MB, sorted by size in descending order.
Hint
Youβll need ls, -lSh, and maybe grep or find for filtering.
π§ Recursive Listing β
ls -RPitfall
This lists all files in all subdirectories β can be verbose!
π² Practice Challenge 2 β
Task
List all .sh files in your home directory and subdirectories, showing details and hidden files.
Hint
Combine ls -laR with filtering.
βοΈ Advanced Use: Sort by Size & Type β
ls -lhSls -lXTIP
-S sorts by size, -X sorts by extension.
π― Practice Challenge 3 β
Task
You want to clean up space. List the 5 largest files in /home including hidden ones, in human-readable format.
Hint
Use ls -lahS | head -n 5
π§ͺ Bonus: Use with Aliases β
echo "alias ll='ls -alh'" >> ~/.bashrc && source ~/.bashrcTIP
Now ll will give you a long listing of all files including hidden ones.
β Summary β
lsis versatile and works best with options.- Combine flags for power:
-alh,-lt,-lhS - Donβt forget
-Rand--color=autofor visibility and depth. - Practice challenges make you internalize the real-world usage.
π§ Final Challenge (Project Style) β
Task
Create a script that logs the top 10 largest .log files from /var/log, sorted by size, including the date/time of the scan.
#!/bin/bash
echo "Log scan on $(date)" > scan.log
ls -lhS /var/log/*.log | head -n 10 >> scan.log
cat scan.logHappy hacking π§π‘
Use the shell, Luke. π§