Managing Uncommitted Changes and Files

These commands are helpful utilities not directly related to core Git functionality, but they are valuable for managing your working directory.

Git Stash

The git stash command temporarily saves uncommitted changes in your working directory. This is helpful when you need to switch branches or work on a different task without committing your current, incomplete work.

  • git stash: Saves your current changes.
  • git stash list: Lists all stashed changes. Stashes are numbered, with 0 being the most recent.
  • git stash apply: Applies the stashed changes. Use git stash apply stash@{<number>} to apply a specific stash.
  • git stash pop: Applies the most recent stash and removes it from the stash list.

Workflow Example:

  1. You’re working on a feature branch.
  2. Your boss asks you to urgently fix a bug on the main branch.
  3. git stash: Saves your uncommitted changes.
  4. git switch main: Switch to the main branch to fix the bug.
  5. Fix the bug and commit the changes to main.
  6. git switch <feature-branch>: Switch back to your feature branch.
  7. git stash pop: Retrieves your saved changes and removes them from the stash list. If you have multiple stashes, use git stash apply stash@{<number>}.

2. Git Clean:

The git clean command removes untracked files and directories from your working directory. This helps maintain a clean workspace.

  • git clean -n: (Dry run) Shows what files would be removed without actually deleting them.
  • git clean -f: Removes untracked files.
  • git clean -d: Removes untracked directories.
  • git clean -fd: Removes untracked files and directories. Use with caution!

Caution: Always use the -n (dry run) option first to see what will be removed before using -f or -fd. git clean -fd is powerful but potentially dangerous; if you’re unsure, back up your work before using it. git clean only affects untracked files; it does not affect tracked files (files that are known to Git).

These commands are helpful for keeping your workspace organized and for managing situations where you need to temporarily put aside your work. Remember to always be cautious when using git clean -fd to avoid accidentally deleting important files.