Terminal Basics
Opening Terminal
bash
1# Spotlight → type "Terminal" → Enter2# Or: Applications → Utilities → Terminal3
4# Popular terminal alternatives:5# iTerm2, Warp, Alacritty, Kitty, HyperEssential Keyboard Shortcuts
bash
1Ctrl + A # Move cursor to beginning of line2Ctrl + E # Move cursor to end of line3Ctrl + U # Delete entire line (before cursor)4Ctrl + K # Delete to end of line5Ctrl + W # Delete word before cursor6Ctrl + R # Reverse search command history7Ctrl + C # Cancel current command8Ctrl + D # Exit shell / EOF9Ctrl + Z # Suspend current process (resume with fg)10Ctrl + L # Clear screen (same as clear)11Tab # Autocomplete file/directory names12Tab Tab # Show all possible completionsCommand History
bash
1history # Show command history2history 20 # Show last 20 commands3!! # Re-run the last command4!n # Run command number n from history5!string # Run last command starting with "string"6!$ # Last argument of previous command7Ctrl + R # Reverse search through history8fc # Open last command in editorShell Configuration
Zsh Config Files (Default Shell)
bash
1~/.zshrc # Main zsh config (loaded for interactive shells)2~/.zprofile # Login shell config (loaded once at login)3~/.zshenv # Always loaded (all zsh invocations)4~/.zsh_history # Command history file5~/.zlogout # Executed on logoutBash Config Files (Legacy)
bash
1~/.bash_profile # Login shell config2~/.bashrc # Interactive non-login shell config3~/.bash_history # Command history4~/.bash_logout # Executed on logoutUseful Aliases
bash
1# Add to ~/.zshrc2alias ll='ls -la'3alias la='ls -A'4alias l='ls -CF'5alias ..='cd ..'6alias ...='cd ../..'7alias cls='clear'8alias grep='grep --color=auto'9alias rm='rm -i' # Confirm before deleting10alias cp='cp -i' # Confirm before overwriting11alias mv='mv -i' # Confirm before overwriting12alias ports='lsof -i -P -n | grep LISTEN'13alias myip='curl -s ifconfig.me'14alias flushdns='sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder'Environment Variables
bash
1echo $PATH # Show current PATH2echo $HOME # Home directory3echo $SHELL # Current shell4echo $USER # Current username5printenv # List all environment variables6export VAR_NAME="value" # Set environment variable (current session)7# Add to ~/.zshrc for persistence:8export PATH="$HOME/bin:$PATH" # Prepend to PATHChange Default Shell
bash
1chsh -s /bin/zsh # Switch to zsh2chsh -s /bin/bash # Switch to bash3cat /etc/shells # List available shells4echo $SHELL # Show current default shellImportant macOS Paths
System Directories
bash
1/ # Root filesystem2/System/ # macOS system files (read-only, SIP protected)3/Library/ # System-wide libraries and support files4~/Library/ # User-specific libraries and app data5/Applications/ # Installed applications6/Users/ # User home directories7/usr/local/ # Homebrew (Intel Mac) and local software8/opt/homebrew/ # Homebrew (Apple Silicon)9/private/var/ # Variable data (logs, tmp, etc.)10/private/etc/ # System configuration files11/tmp/ # Temporary files (symlink to /private/tmp)Configuration & Preferences
bash
1~/Library/Preferences/ # App preference files (.plist)2~/Library/Application Support/ # App data and configs3~/Library/Caches/ # App cache files4~/Library/Logs/ # User app logs5~/Library/LaunchAgents/ # User-level launch agents (auto-start)6/Library/LaunchAgents/ # System-wide launch agents7/Library/LaunchDaemons/ # System-wide launch daemons (root services)8~/Library/Containers/ # Sandboxed app data9~/Library/Group Containers/ # Shared data between appsLog Files
bash
1/var/log/system.log # Main system log (legacy)2/var/log/install.log # Installation logs3/var/log/wifi.log # Wi-Fi logs4/var/log/apache2/ # Apache web server logs5~/Library/Logs/ # User application logs6~/Library/Logs/DiagnosticReports/ # Crash reports7# Modern macOS uses unified logging:8log show --last 1h # Show last hour of logs9log show --predicate 'process == "kernel"' --last 30m # Kernel logs10log stream # Live log streamFile & Directory Management
Navigation
bash
1pwd # Print current directory2cd /path/to/dir # Change directory3cd ~ # Go to home directory4cd - # Go to previous directory5cd .. # Go up one level6cd ../.. # Go up two levels7pushd /path/to/dir # Push directory onto stack and cd8popd # Pop directory from stack and cd back9dirs -v # Show directory stackListing Files
bash
1ls # List files2ls -l # Long format (permissions, size, date)3ls -la # Long format including hidden files4ls -lh # Long format with human-readable sizes5ls -lS # Sort by file size (largest first)6ls -lt # Sort by modification time (newest first)7ls -lR # List recursively8ls -1 # One file per line9ls -d */ # List only directoriesCreating Files & Directories
bash
1touch file.txt # Create empty file or update timestamp2mkdir dirname # Create directory3mkdir -p path/to/nested/dir # Create nested directories4mktemp # Create a temporary file5mktemp -d # Create a temporary directoryCopying, Moving & Renaming
bash
1cp source.txt dest.txt # Copy file2cp -r source_dir/ dest_dir/ # Copy directory recursively3cp -i source.txt dest.txt # Interactive (confirm overwrite)4mv oldname.txt newname.txt # Rename file5mv file.txt /path/to/dest/ # Move file6ditto source/ dest/ # macOS-native copy (preserves metadata)7ditto -V source/ dest/ # Verbose ditto copy8rsync -av source/ dest/ # Sync files (fast incremental copy)9rsync -av --delete src/ dest/ # Sync and delete extra files in destDeleting Files & Directories
bash
1rm file.txt # Delete file2rm -f file.txt # Force delete (no confirmation)3rm -r dirname/ # Delete directory recursively4rm -rf dirname/ # Force delete directory5rmdir dirname # Delete empty directory only6trash file.txt # Move to Trash (if trash CLI installed)7# macOS native: move to Trash via Finder or use `mv file ~/.Trash/`File Permissions & Ownership
bash
1chmod 755 script.sh # Set permissions (rwxr-xr-x)2chmod +x script.sh # Add execute permission3chmod -R 644 directory/ # Set permissions recursively4chown user:group file.txt # Change file owner and group5chown -R user:group dir/ # Change owner recursively6ls -l # View permissions7stat -f '%A %N' file.txt # Show octal permissions (macOS)Links
bash
1ln -s /path/to/original link # Create symbolic link2ln /path/to/original hardlink # Create hard link3readlink link_name # Show where symlink points4ls -la # Symlinks shown with -> targetViewing & Editing Files
Viewing File Contents
bash
1cat file.txt # Display entire file2less file.txt # View file (scrollable, press q to quit)3more file.txt # View file (page by page)4head file.txt # Show first 10 lines5head -n 20 file.txt # Show first 20 lines6tail file.txt # Show last 10 lines7tail -n 20 file.txt # Show last 20 lines8tail -f logfile.log # Follow file in real-time (great for logs)9wc file.txt # Count lines, words, bytes10wc -l file.txt # Count lines onlyText Editors (Terminal)
bash
1nano file.txt # Simple editor (Ctrl+O save, Ctrl+X exit)2vi file.txt # Vi editor (i=insert, Esc :wq=save+quit)3vim file.txt # Vim (improved vi)4open -e file.txt # Open in TextEdit5code file.txt # Open in VS Code (if installed)File Information
bash
1file myfile # Detect file type2stat file.txt # Detailed file info (size, dates, etc.)3mdls file.txt # Spotlight metadata attributes4xattr file.txt # List extended attributes5xattr -d com.apple.quarantine file # Remove quarantine flag6GetFileInfo file.txt # HFS+ attributesSearching & Finding
Find Files
bash
1find / -name "filename" # Find file by name (whole system)2find . -name "*.txt" # Find .txt files in current dir3find . -type f -name "*.log" # Find files only (not directories)4find . -type d -name "src" # Find directories only5find . -size +100M # Find files larger than 100MB6find . -mtime -7 # Files modified in last 7 days7find . -mtime +30 # Files modified more than 30 days ago8find . -empty # Find empty files and directories9find . -name "*.tmp" -delete # Find and delete files10find . -name "*.sh" -exec chmod +x {} \; # Find and execute commandSpotlight Search (macOS-Specific)
bash
1mdfind "search query" # Search using Spotlight index2mdfind -name "filename" # Search by filename3mdfind -onlyin ~/Documents "report" # Search in specific directory4mdfind "kMDItemKind == 'PDF'" # Search by file kind5mdls file.txt # Show Spotlight metadata for a file6mdutil -s / # Check Spotlight indexing status7mdutil -E / # Erase and rebuild Spotlight indexSearch Inside Files
bash
1grep "pattern" file.txt # Search for pattern in file2grep -r "pattern" directory/ # Search recursively in directory3grep -i "pattern" file.txt # Case-insensitive search4grep -n "pattern" file.txt # Show line numbers5grep -l "pattern" *.txt # List files containing pattern6grep -c "pattern" file.txt # Count matching lines7grep -v "pattern" file.txt # Show lines NOT matching8grep -E "regex" file.txt # Extended regex (egrep)Locate Files
bash
1locate filename # Fast file search using database2sudo /usr/libexec/locate.updatedb # Update locate database3which command # Show path of a command4whereis command # Show binary/man/source paths5type command # Show how command would be interpretedText Processing
Common Tools
bash
1sort file.txt # Sort lines alphabetically2sort -n file.txt # Sort numerically3sort -r file.txt # Reverse sort4sort -u file.txt # Sort and remove duplicates5uniq file.txt # Remove adjacent duplicate lines6uniq -c file.txt # Count occurrences of each line7cut -d',' -f1,3 data.csv # Extract columns 1 and 3 (comma delimited)8cut -c1-10 file.txt # Extract first 10 characters per line9paste file1.txt file2.txt # Merge lines of files side-by-side10tr 'a-z' 'A-Z' < file.txt # Convert to uppercase11tr -d '\r' < file.txt # Remove carriage returns (Windows → Unix)sed & awk
bash
1sed 's/old/new/' file.txt # Replace first occurrence per line2sed 's/old/new/g' file.txt # Replace all occurrences3sed -i '' 's/old/new/g' file # In-place edit (macOS sed)4sed -n '5,10p' file.txt # Print lines 5 to 105awk '{print $1}' file.txt # Print first column6awk -F',' '{print $2}' data.csv # Print 2nd column (comma delimiter)7awk '{sum+=$1} END {print sum}' file.txt # Sum first columnRedirection & Pipes
bash
1command > file.txt # Redirect stdout to file (overwrite)2command >> file.txt # Append stdout to file3command 2> error.log # Redirect stderr to file4command &> output.log # Redirect stdout and stderr5command 2>&1 # Redirect stderr to stdout6command1 | command2 # Pipe output of cmd1 to cmd27command | tee file.txt # Output to screen AND file8command | tee -a file.txt # Append to file AND show on screenSystem Information
macOS Version & Hardware
bash
1sw_vers # macOS version details2sw_vers -productVersion # Just the version number3uname -a # Kernel version and architecture4uname -m # CPU architecture (arm64 / x86_64)5system_profiler SPHardwareDataType # Detailed hardware info6system_profiler SPSoftwareDataType # Software overview7sysctl -n machdep.cpu.brand_string # CPU model name8sysctl -n hw.memsize # Total memory (bytes)9sysctl hw.ncpu # Number of CPUs10arch # Print architecture (arm64 / i386)Disk & Storage
bash
1df -h # Disk space usage (human-readable)2df -H # Disk space (powers of 1000)3du -sh * # Size of each item in current dir4du -sh directory/ # Total size of a directory5du -sh * | sort -rh | head -10 # Top 10 largest items6diskutil list # List all disks and partitions7diskutil info disk0 # Info about a specific disk8diskutil apfs list # List APFS volumes9diskutil eraseDisk APFS "Name" disk2 # Erase and format diskMemory & CPU
bash
1top # Real-time process monitor (q to quit)2htop # Improved top (install via brew)3top -l 1 -s 0 | head -n 12 # Snapshot of system stats4vm_stat # Virtual memory statistics5sysctl hw.memsize # Total physical memory6memory_pressure # Memory pressure status7powermetrics --samplers cpu_power -n 1 # CPU power usage (sudo)Uptime & Users
bash
1uptime # System uptime and load average2w # Who is logged in and what they're doing3who # Currently logged in users4whoami # Current username5id # Current user ID, group ID6last # List last loginsProcess Management
Viewing Processes
bash
1ps aux # All running processes (detailed)2ps aux | grep process_name # Find a specific process3pgrep -l process_name # Find process by name (with PID)4top # Real-time process viewer5top -o cpu # Sort by CPU usage6top -o mem # Sort by memory usage7lsof # List all open files8lsof -i :8080 # What is using port 80809lsof -c process_name # Files opened by a processKilling Processes
bash
1kill PID # Send TERM signal to process2kill -9 PID # Force kill (SIGKILL)3kill -HUP PID # Send hangup signal (reload config)4killall process_name # Kill all processes by name5killall -9 process_name # Force kill all by name6pkill process_name # Kill by partial name match7pkill -f "pattern" # Kill by full command line matchBackground & Foreground
bash
1command & # Run command in background2jobs # List background jobs3fg # Bring last job to foreground4fg %1 # Bring job 1 to foreground5bg %1 # Resume job 1 in background6nohup command & # Run command immune to hangup (persists after logout)7disown %1 # Detach job from shellLaunch Agents & Daemons (Startup Services)
bash
1launchctl list # List all loaded services2launchctl list | grep my-service # Find a specific service3launchctl load ~/Library/LaunchAgents/com.my.plist # Load/start a service4launchctl unload ~/Library/LaunchAgents/com.my.plist # Unload/stop a service5launchctl start com.my.service # Start a service by label6launchctl stop com.my.service # Stop a service by label7sudo launchctl kickstart -k system/com.apple.mDNSResponder # Restart system serviceNetworking
Network Information
bash
1ifconfig # Show network interfaces2ifconfig en0 # Show Wi-Fi interface details3ipconfig getifaddr en0 # Get local IP address (Wi-Fi)4curl -s ifconfig.me # Get public IP address5curl -s ipinfo.io # Detailed public IP info (JSON)6networksetup -listallhardwareports # List all network ports7networksetup -getinfo Wi-Fi # Wi-Fi connection info8scutil --dns # Show DNS configuration9cat /etc/resolv.conf # DNS resolver config10hostname # Show hostname11scutil --get HostName # Get hostname12sudo scutil --set HostName name # Set hostnameTesting Connectivity
bash
1ping google.com # Ping a host (Ctrl+C to stop)2ping -c 5 google.com # Ping 5 times then stop3traceroute google.com # Trace route to host4mtr google.com # Combined ping + traceroute (install via brew)5curl -I https://example.com # HTTP headers only6curl -o file.zip https://url # Download file7curl -L https://url # Follow redirects8wget https://url # Download file (install via brew)9networkQuality # Test network quality (macOS 12+)10networkQuality -v # Verbose network quality testDNS
bash
1nslookup domain.com # DNS lookup2dig domain.com # Detailed DNS lookup3dig domain.com +short # Short DNS answer4host domain.com # Simple DNS lookup5dscacheutil -flushcache # Flush DNS cache6sudo killall -HUP mDNSResponder # Restart DNS resolverPorts & Connections
bash
1netstat -an # Show all connections2netstat -an | grep LISTEN # Show listening ports3lsof -i -P -n # List all network connections4lsof -i :80 # What is using port 805lsof -i :8080 # What is using port 80806sudo lsof -iTCP -sTCP:LISTEN -n -P # All listening TCP portsFirewall
bash
1sudo pfctl -s info # Packet filter info2sudo pfctl -e # Enable firewall3sudo pfctl -d # Disable firewall4sudo pfctl -f /etc/pf.conf # Reload firewall rules5/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate # App firewall status6sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on # Enable app firewallSSH
bash
1ssh user@hostname # Connect to remote host2ssh -p 2222 user@hostname # Connect on custom port3ssh -i ~/.ssh/key.pem user@host # Connect with specific key4ssh-keygen -t ed25519 # Generate SSH key (recommended type)5ssh-keygen -t rsa -b 4096 # Generate RSA SSH key6ssh-copy-id user@hostname # Copy public key to remote host7scp file.txt user@host:/path/ # Secure copy file to remote8scp user@host:/path/file.txt . # Secure copy file from remote9scp -r dir/ user@host:/path/ # Copy directory recursivelyPackage Management (Homebrew)
Install Homebrew
bash
1# Install Homebrew2/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"3
4# Verify installation5brew --versionCommon Homebrew Commands
bash
1brew search package # Search for a package2brew install package # Install a package3brew uninstall package # Uninstall a package4brew list # List installed packages5brew info package # Show package info6brew update # Update Homebrew itself7brew upgrade # Upgrade all packages8brew upgrade package # Upgrade specific package9brew outdated # List outdated packages10brew cleanup # Remove old versions11brew cleanup -s # Remove all cached downloads12brew doctor # Diagnose issues13brew deps package # Show dependencies14brew uses package --installed # Show what depends on a packageHomebrew Casks (GUI Applications)
bash
1brew install --cask app-name # Install GUI application2brew uninstall --cask app-name # Uninstall GUI application3brew list --cask # List installed casks4brew outdated --cask # List outdated casks5brew upgrade --cask # Upgrade all casks6
7# Common casks:8brew install --cask google-chrome9brew install --cask visual-studio-code10brew install --cask iterm211brew install --cask docker12brew install --cask rectangle # Window managementHomebrew Services
bash
1brew services list # List all services2brew services start service # Start a service3brew services stop service # Stop a service4brew services restart service # Restart a service5brew services run service # Run without auto-start on loginDisk & Volume Management
Disk Utility CLI
bash
1diskutil list # List all disks and partitions2diskutil info /dev/disk0 # Info about a specific disk3diskutil mountDisk /dev/disk2 # Mount a disk4diskutil unmountDisk /dev/disk2 # Unmount a disk5diskutil eject /dev/disk2 # Eject external disk6diskutil mount /dev/disk2s1 # Mount a specific partition7diskutil unmount /dev/disk2s1 # Unmount a specific partition8diskutil verifyVolume / # Verify boot volume9diskutil repairVolume / # Repair boot volume10diskutil apfs list # List APFS containers and volumesMounts & Filesystems
bash
1mount # Show all mounted filesystems2mount | grep -i "disk" # Show disk mounts3mount_smbfs //user@server/share /mnt # Mount SMB share4umount /mnt/point # Unmount a filesystem5hdiutil attach disk-image.dmg # Mount a DMG image6hdiutil detach /dev/disk2 # Unmount a DMG image7hdiutil create -size 1g -fs APFS -volname "MyDisk" my.dmg # Create DMGCompression & Archives
Common Commands
bash
1# ZIP2zip archive.zip file1 file2 # Create zip archive3zip -r archive.zip directory/ # Zip a directory recursively4unzip archive.zip # Extract zip5unzip -l archive.zip # List contents without extracting6
7# TAR8tar -czf archive.tar.gz dir/ # Create gzipped tarball9tar -cjf archive.tar.bz2 dir/ # Create bzip2 tarball10tar -xzf archive.tar.gz # Extract gzipped tarball11tar -xjf archive.tar.bz2 # Extract bzip2 tarball12tar -tf archive.tar.gz # List contents of tarball13tar -xzf archive.tar.gz -C /dest/ # Extract to specific directory14
15# GZIP16gzip file.txt # Compress (replaces original)17gzip -k file.txt # Compress (keep original)18gunzip file.txt.gz # DecompressUser & Permissions Management
User Information
bash
1whoami # Current username2id # User ID, group ID, groups3id -un # Username only4groups # List groups for current user5dscl . list /Users # List all local users6dscl . list /Groups # List all local groups7dscl . read /Users/username # User details8finger username # User infoSudo & Privileges
bash
1sudo command # Run command as root2sudo -s # Open root shell3sudo -u user command # Run command as another user4sudo !! # Re-run last command with sudo5visudo # Edit sudoers file safelymacOS-Specific Commands
System Preferences & Defaults
bash
1# Show hidden files in Finder2defaults write com.apple.finder AppleShowAllFiles -bool true3killall Finder4
5# Hide hidden files again6defaults write com.apple.finder AppleShowAllFiles -bool false7killall Finder8
9# Show full path in Finder title bar10defaults write com.apple.finder _FNDShowPathbar -bool true11
12# Screenshot location13defaults write com.apple.screencapture location ~/Desktop/Screenshots14killall SystemUIServer15
16# Screenshot format (png, jpg, pdf, tiff)17defaults write com.apple.screencapture type png18
19# Disable screenshot shadow20defaults write com.apple.screencapture disable-shadow -bool true21
22# Show all file extensions23defaults write NSGlobalDomain AppleShowAllExtensions -bool true24
25# Disable auto-correct26defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false27
28# Key repeat speed (lower = faster)29defaults write NSGlobalDomain KeyRepeat -int 230defaults write NSGlobalDomain InitialKeyRepeat -int 1531
32# Read current default33defaults read com.apple.finder AppleShowAllFilesOpen Command
bash
1open . # Open current directory in Finder2open file.txt # Open file with default app3open -a "Safari" https://url # Open URL in Safari4open -a "Visual Studio Code" . # Open current dir in VS Code5open -R file.txt # Reveal file in Finder6open /Applications/ # Open Applications folder7open -e file.txt # Open in TextEditScreenshots
bash
1screencapture screen.png # Full screen capture2screencapture -i region.png # Interactive region capture3screencapture -w window.png # Capture specific window4screencapture -c # Capture to clipboard5screencapture -T 5 delayed.png # Capture after 5-second delay6screencapture -x silent.png # Capture without soundClipboard
bash
1echo "text" | pbcopy # Copy text to clipboard2pbpaste # Paste from clipboard3pbpaste > file.txt # Paste clipboard to file4cat file.txt | pbcopy # Copy file contents to clipboard5pbpaste | sort | pbcopy # Sort clipboard contentsSay (Text to Speech)
bash
1say "Hello World" # Read text aloud2say -f file.txt # Read file aloud3say -v ? # List available voices4say -v Samantha "Hello" # Use specific voice5say -o output.aiff "Hello" # Save speech to audio fileSystem Control
bash
1sudo shutdown -h now # Shutdown immediately2sudo shutdown -h +30 # Shutdown in 30 minutes3sudo shutdown -r now # Restart immediately4sudo reboot # Restart5pmset sleepnow # Put Mac to sleep6caffeinate # Prevent sleep (Ctrl+C to stop)7caffeinate -t 3600 # Prevent sleep for 1 hour8caffeinate -s # Prevent sleep while on AC power9osascript -e 'tell app "System Events" to log out' # Log outSoftware Updates
bash
1softwareupdate -l # List available updates2softwareupdate -ia # Install all available updates3softwareupdate -ir # Install recommended updates4softwareupdate --history # Show update historySpotlight
bash
1mdutil -s / # Check Spotlight indexing status2mdutil -i on / # Enable Spotlight indexing3mdutil -i off / # Disable Spotlight indexing4mdutil -E / # Erase and rebuild index5mdfind "search term" # Search via Spotlight6mdfind -name "filename" # Search files by nameSecurity & Privacy
bash
1# System Integrity Protection (SIP)2csrutil status # Check SIP status3# To enable/disable SIP, boot into Recovery Mode (Cmd+R)4
5# Gatekeeper6spctl --status # Check Gatekeeper status7sudo spctl --master-disable # Disable Gatekeeper8sudo spctl --master-enable # Enable Gatekeeper9
10# Keychain11security find-generic-password -a "account" -s "service" # Find password12security list-keychains # List keychains13
14# FileVault (disk encryption)15fdesetup status # Check FileVault status16sudo fdesetup enable # Enable FileVaultGit Quick Reference
Basic Commands
bash
1git init # Initialize repository2git clone url # Clone repository3git status # Check status4git add . # Stage all changes5git add file.txt # Stage specific file6git commit -m "message" # Commit with message7git push # Push to remote8git pull # Pull from remoteBranching
bash
1git branch # List branches2git branch new-branch # Create branch3git checkout branch-name # Switch branch4git checkout -b new-branch # Create and switch5git merge branch-name # Merge branch6git branch -d branch-name # Delete branchUseful Git Commands
bash
1git log --oneline # Compact log2git log --graph --oneline # Visual branch log3git diff # Show unstaged changes4git stash # Stash changes5git stash pop # Apply stashed changes6git remote -v # Show remotes7git reset --hard HEAD # Discard all changesCron & Scheduling
Crontab
bash
1crontab -l # List cron jobs2crontab -e # Edit cron jobs3crontab -r # Remove all cron jobsCron Syntax
bash
1# ┌───────── minute (0 - 59)2# │ ┌─────── hour (0 - 23)3# │ │ ┌───── day of month (1 - 31)4# │ │ │ ┌─── month (1 - 12)5# │ │ │ │ ┌─ day of week (0 - 7, 0 and 7 = Sunday)6# │ │ │ │ │7# * * * * * command8
9# Examples:100 * * * * command # Every hour11*/15 * * * * command # Every 15 minutes120 9 * * 1-5 command # Weekdays at 9 AM130 0 * * * command # Daily at midnight140 0 1 * * command # First of every month15@reboot command # At startupUseful One-Liners
File Operations
bash
1# Find and delete .DS_Store files2find . -name ".DS_Store" -delete3
4# Find large files (>100MB)5find / -type f -size +100M 2>/dev/null6
7# Count files in directory8find . -type f | wc -l9
10# Compare two directories11diff -rq dir1/ dir2/12
13# Generate a file checksum14shasum -a 256 file.txt15md5 file.txtSystem Maintenance
bash
1# Free up disk space2brew cleanup && rm -rf ~/Library/Caches/*3
4# Show top 20 largest files5find / -type f -exec du -h {} + 2>/dev/null | sort -rh | head -206
7# List all listening ports with process names8sudo lsof -iTCP -sTCP:LISTEN -n -P9
10# Kill process on a specific port11lsof -ti :3000 | xargs kill -912
13# Watch a command run every 2 seconds14watch -n 2 'kubectl get pods' # (install via brew)Text & Data
bash
1# Count lines in all .py files2find . -name "*.py" -exec cat {} + | wc -l3
4# Remove duplicate lines from a file5sort file.txt | uniq > cleaned.txt6
7# Generate a random password8openssl rand -base64 249
10# Generate UUID11uuidgen12
13# Encode/decode base6414echo "text" | base64 # Encode15echo "dGV4dAo=" | base64 -d # Decode16
17# JSON pretty print18cat file.json | python3 -m json.tool19echo '{"key":"val"}' | jq . # Using jq (install via brew)Common Shortnames & Aliases
| Abbreviation | Full Form |
|---|---|
~ | Home directory (/Users/username) |
. | Current directory |
.. | Parent directory |
- | Previous directory (for cd) |
/ | Root directory |
* | Wildcard (matches any characters) |
? | Wildcard (matches single character) |
> | Redirect output (overwrite) |
>> | Redirect output (append) |
| ` | ` |
& | Run command in background |
&& | Run next command if previous succeeds |
| ` | |
; | Run next command regardless |
!! | Repeat last command |
!$ | Last argument of previous command |