Chapter 3: File System Navigation and Manipulation¶
Learning Objectives¶
By the end of this chapter, you will be able to:
- Navigate the macOS file system using Bash commands
- Understand relative vs absolute paths
- Manage files and directories: create, delete, move, and copy
- Use wildcards and globbing for pattern matching
- Apply file permissions and understand
chmod,chown, andumask - Use macOS-specific tools like
open,xattr, andmdls
Introduction: The Shell as Your Filesystem Interface¶
The command line isn't just a place to run commands — it's a powerful interface to the file system. In this chapter, we'll explore how to traverse, inspect, and modify files and directories using Bash, with a focus on macOS's quirks and features.
3.1 Paths: Absolute vs Relative¶
- Absolute path: starts from root
/ - Example:
/Users/sammy/Documents/report.txt(use$HOME/Documents/report.txtin scripts) - Relative path: based on your current directory
- Example:
../Documents/report.txt
Check your current directory:
Move to another directory:
Return to previous directory:
3.2 Listing and Inspecting Files¶
List directory contents:
Inspect file metadata:
macOS-specific:
3.3 Creating and Removing Files and Directories¶
Create a file or folder:
Delete files or folders:
Be cautious with rm -rf. It will remove without confirmation.
3.4 Moving, Copying, and Renaming¶
Move or rename:
Copy files and folders:
Use -i to confirm before overwriting.
3.5 Wildcards and Globbing¶
Use wildcards to match file patterns:
*matches any characters?matches a single character[]matches a character set
Examples:
ls *.txt # All .txt files
ls report?.pdf # report1.pdf, report2.pdf, etc.
ls data[1-3].csv # data1.csv, data2.csv, data3.csv
Combine with commands like rm, cp, echo, etc.
3.6 Permissions and Ownership¶
Check permissions:
Modify permissions:
Change ownership (admin required):
Default permission mask:
3.7 macOS-Specific File Tips¶
- Use
open .to launch Finder open file.pdfopens with default app- Use
mdls,xattr,GetFileInfofor metadata - Spotlight indexing can interfere with scripting; exclude folders via:
Chapter 3 Exercise¶
Write a script named organize_downloads.sh that:
- Scans your
~/Downloadsdirectory - Moves
.zipfiles to~/Downloads/zips - Moves
.dmgfiles to~/Downloads/installers - Creates folders if they don’t exist
Hint:
#!/bin/bash
mkdir -p ~/Downloads/zips ~/Downloads/installers
for file in ~/Downloads/*; do
case "$file" in
*.zip) mv "$file" ~/Downloads/zips/ ;;
*.dmg) mv "$file" ~/Downloads/installers/ ;;
esac
done
echo "Downloads organized."
macOS Scripting Tips¶
open -R filenamereveals a file in Finder- Use
tmutilto interact with Time Machine in scripts - Use
diskutil listto inspect drives and volumes - Use
findormdfindfor search with greater flexibility