git_terminalbench 95 Q&As

Git Terminalbench FAQ & Answers

95 expert Git Terminalbench answers researched from official documentation. Every answer cites authoritative sources you can verify.

Git Server Setup

12 questions
A

For read-only HTTP access, point any web server to the git directory. With nginx: server { listen 8080; location / { root /srv/git; autoindex on; } }. For smart HTTP (push support), use git-http-backend CGI: configure nginx with fcgiwrap to execute /usr/lib/git-core/git-http-backend. Enable hooks for post-receive deployment.

95% confidence
A

Step-by-step setup: 1) Install SSH server: apt-get install -y openssh-server && mkdir -p /var/run/sshd && service ssh start. 2) Enable password auth: edit /etc/ssh/sshd_config, set PasswordAuthentication yes, restart: service ssh restart. 3) Create git user (or use existing): adduser git or set password echo 'root:password' | chpasswd. 4) Create bare repo: git init --bare /srv/git/myproject.git. 5) Set permissions: chown -R git:git /srv/git (if using git user). 6) Test: From client run git ls-remote ssh://user@host/srv/git/myproject.git to verify access. 7) Clone: git clone ssh://user@host/srv/git/myproject.git. IMPORTANT: Verify each step works before proceeding to the next.

95% confidence
A

Use the format: git clone username@hostname:/path/to/repo.git or git clone ssh://username@hostname/path/to/repo.git. For example: git clone [email protected]:user/repo.git. Ensure your SSH public key is added to the server's authorized_keys file or the hosting service. SSH provides secure, encrypted communication without transmitting passwords.

95% confidence
A
  1. Create a git user: sudo adduser git. 2) Set up SSH: su git && cd && mkdir .ssh && chmod 700 .ssh && touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys. 3) Add developer public keys to authorized_keys. 4) Create bare repository: git init --bare /srv/git/project.git. 5) Users can now clone via: git clone git@server:/srv/git/project.git. For security, restrict git user's shell to git-shell.
95% confidence
A

Use scp or rsync to copy the bare repository: scp -r my_project.git user@server:/srv/git/. Once copied, users can clone from it. Ensure the git user has read/write permissions on the repository directory. The repository is immediately usable after copying - no additional setup needed.

95% confidence
A

A non-bare repository has a working directory with checked-out files plus a .git folder containing version control data. A bare repository contains only the .git directory contents without a working directory - you cannot edit files directly in it. Bare repositories are used as central/remote repositories for sharing, while non-bare repositories are used for development work.

95% confidence
A

Use git ls-remote to test SSH access without modifying anything: git ls-remote ssh://user@host/path/to/repo.git. This connects to the server and lists refs. Success means: SSH auth works, git protocol works, repo exists and is accessible. If it fails: check SSH connection first with ssh user@host 'echo SSH OK', then verify repo path exists. For password auth, you'll be prompted for password. For automated testing: GIT_SSH_COMMAND='sshpass -p password ssh -o StrictHostKeyChecking=no' git ls-remote ssh://user@host/path/to/repo.git.

95% confidence
A

Use git init --bare /path/to/repo.git. A bare repository has no working directory - it contains only the .git directory contents (objects, refs, HEAD, etc.). Bare repositories are used as central shared repositories on servers. By convention, bare repository names end with .git extension. You can also create one by cloning: git clone --bare my_project my_project.git.

95% confidence
A

Client-side workflow: 1) Configure git identity: git config user.name 'Name' && git config user.email 'email'. 2) Add remote: git remote add origin ssh://user@host/path/to/repo.git. 3) Create and commit: echo 'content' > file.txt && git add . && git commit -m 'Initial'. 4) Push: git push -u origin main. If push fails with 'non-fast-forward': for new repos use git push -u origin main; for existing use git push --force (careful!). Verify deployment: Check target directory or curl the web server. The post-receive hook runs automatically after successful push.

95% confidence
A

When a task specifies git@localhost:/path/to/repo, you MUST create a user named git:

# Create git user with home directory and bash shell
useradd -m -s /bin/bash git

# Set the password (if password auth is required)
echo 'git:password' | chpasswd

# Give git user ownership of the repo
chown -R git:git /git/project

CRITICAL: The username in git@localhost is the SSH username. If task says git@localhost, do NOT use root - create a git user.

Common mistake: Setting root:password when task says git@localhost. This will fail because SSH will connect as user git, not root.

Verify the user exists and has password:

id git  # Should show uid and gid
su - git -c 'echo User works'  # Should work with password
95% confidence
A

Always verify each component independently before integrating: 1) SSH Server: service ssh status then ssh localhost echo OK. 2) Git bare repo: ls /path/to/repo.git/HEAD confirms valid repo. 3) Git over SSH: git ls-remote ssh://user@host/path/to/repo.git tests full path. 4) Post-receive hook: Check ls -la hooks/post-receive is executable, test manually with echo 'old new refs/heads/main' | hooks/post-receive. 5) Web server: curl -I http://localhost:port or curl -k https://localhost:port. 6) Deployment directory: ls -la /var/www/html exists and writable. Key principle: if any step fails, debug that step before moving on. Don't assume earlier steps worked.

95% confidence
A

When task specifies git@localhost:/git/project with password "password", follow this EXACT order:

  1. Install packages:
apt-get update && apt-get install -y openssh-server git
mkdir -p /var/run/sshd
service ssh start
  1. Enable password authentication:
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
service ssh restart
  1. Create the user from the URL (git@localhost means user 'git'):
useradd -m -s /bin/bash git
echo 'git:password' | chpasswd
  1. Create and configure repo:
mkdir -p /git
git init --bare /git/project
chown -R git:git /git
  1. VERIFY before proceeding:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no git@localhost 'echo OK'
# Should prompt for password and print OK

CRITICAL: The user in the URL (git@...) MUST match the user you create. Don't use root when URL says git@.

95% confidence

Branch Management

11 questions
A

Merge creates a new 'merge commit' combining two branches, preserving complete history with all original commits visible. Rebase replays commits from one branch onto another, creating new commits with new hashes - results in linear history. Use merge for public/shared branches (preserves history), rebase for local/feature branches (cleaner history). Never rebase pushed commits others depend on.

95% confidence
A

Apply a single commit to current branch: git cherry-pick <commit-hash>. Multiple commits: git cherry-pick <hash1> <hash2>. Range: git cherry-pick A..B (excludes A, includes B). With -x flag adds source reference to message. If conflicts occur: resolve, stage, then git cherry-pick --continue. Abort with git cherry-pick --abort. Use sparingly - can create duplicate commits.

95% confidence
A

Traditional: git checkout -b <branch-name> creates and switches. Modern (Git 2.23+): git switch -c <branch-name>. From specific commit: git checkout -b <branch> <commit> or git switch -c <branch> <commit>. Create without switching: git branch <branch-name>. Then switch: git checkout <branch> or git switch <branch>.

95% confidence
A

Save changes: git stash or git stash push -m 'description'. List stashes: git stash list. Apply and keep stash: git stash apply or git stash apply stash@{n}. Apply and remove stash: git stash pop. Remove specific stash: git stash drop stash@{n}. Clear all: git stash clear. Include untracked: git stash -u. Include ignored: git stash -a.

95% confidence
A

Detached HEAD occurs when HEAD points directly to a commit instead of a branch reference. Happens when checking out a commit hash, tag, or remote branch. Commits made here are orphaned when you switch away. To fix: 1) Create branch from current position: git checkout -b new-branch or git switch -c new-branch, or 2) Switch to existing branch: git checkout main (discards detached commits unless saved).

95% confidence
A

This error occurs when trying to create a branch that already exists. Solutions: 1) Switch to existing branch: git checkout X or git switch X. 2) Delete and recreate: git branch -D X && git checkout -b X. 3) Use different name: git checkout -b X-new. 4) For scripts, check first: git show-ref --verify --quiet refs/heads/X || git branch X. When pushing to bare repo and branch exists, git will update it - no need to recreate. To force checkout even if branch exists: use git checkout -B X (uppercase B forces).

95% confidence
A

Rename current branch: git branch -m <new-name>. Rename any branch: git branch -m <old-name> <new-name>. After renaming, update remote: git push origin -u <new-name> then delete old: git push origin --delete <old-name>. Collaborators need to update: git fetch --all --prune and reset their local tracking.

95% confidence
A

Both restore stashed changes. git stash pop applies changes and removes the stash from the list. git stash apply applies changes but keeps the stash, allowing reuse. If conflicts occur during pop, stash is NOT removed - resolve conflicts manually, then git stash drop. Use apply when you might need the stash again or want to apply to multiple branches.

95% confidence
A

When cloning, tracking is automatic for default branch. Set tracking explicitly: git branch -u origin/<branch> or git branch --set-upstream-to=origin/<branch>. When pushing new branch: git push -u origin <branch>. Check tracking: git branch -vv. Tracking enables git pull and git push without specifying remote/branch.

95% confidence
A

Delete local branch: git branch -d <branch> (safe - won't delete unmerged) or git branch -D <branch> (force delete). Delete remote branch: git push origin --delete <branch> or git push origin :<branch>. Delete local tracking ref: git branch -dr origin/<branch>. Prune deleted remote branches: git fetch --prune.

95% confidence
A

Local branches: git branch. Remote branches: git branch -r. All branches: git branch -a. With last commit info: git branch -v. With tracking info: git branch -vv. Show merged branches: git branch --merged. Show unmerged: git branch --no-merged. Filter by pattern: git branch --list 'feature/*'.

95% confidence

Git Hooks

11 questions
A

Create hooks/post-receive in your bare repo with this script:
#!/bin/bash
while read oldrev newrev refname; do
branch=${refname#refs/heads/}
case "$branch" in
main|master)
echo "Deploying $branch to production..."
git --work-tree=/var/www/html --git-dir=/srv/git/myproject.git checkout -f $branch
;;
dev|develop)
echo "Deploying $branch to staging..."
git --work-tree=/var/www/dev --git-dir=/srv/git/myproject.git checkout -f $branch
;;
esac
done

Make executable: chmod +x hooks/post-receive. Create target directories: mkdir -p /var/www/html /var/www/dev. The hook reads stdin (oldrev newrev refname per line), extracts branch name, and deploys to appropriate directory using git checkout -f with explicit --work-tree and --git-dir flags.

95% confidence
A

Create hooks/post-receive in your bare repo with: #!/bin/bash\nwhile read oldrev newrev ref; do\n if [[ $ref = refs/heads/main ]]; then\n git --work-tree=/var/www/html --git-dir=/path/to/repo.git checkout -f main\n fi\ndone. Make it executable: chmod +x hooks/post-receive. This deploys the main branch to /var/www/html on every push. Unset GIT_DIR if running git commands: unset GIT_DIR.

95% confidence
A

Git hooks are stored in .git/hooks/ (local repo) or hooks/ (bare repo). Sample hooks with .sample extension are provided. To enable a hook: 1) Create/rename the script without .sample extension (e.g., pre-commit), 2) Make it executable: chmod +x .git/hooks/pre-commit. Hooks are not version-controlled by default - commit them elsewhere and symlink or copy during setup.

95% confidence
A

The hook receives stdin with: old-sha new-sha refname. Parse it: while read oldrev newrev refname; do branch=$(basename $refname); if [ "$branch" = "main" ]; then # deploy main; fi; done. The refname is like refs/heads/main. Use this to deploy only specific branches or perform branch-specific actions.

95% confidence
A

The post-receive hook is a server-side script that runs after a push is completely received. Located at hooks/post-receive in a bare repository, it receives stdin data about pushed refs (old-sha new-sha refname). Common uses: auto-deployment, CI triggers, notifications. The hook must be executable (chmod +x). It runs after refs are updated, so it cannot reject the push.

95% confidence
A

The post-commit hook runs after a commit is created. Located at .git/hooks/post-commit, it takes no parameters but can access the last commit via git log -1 HEAD. Common uses: notifications, triggering builds, updating issue trackers. It runs locally after each commit completes. Cannot modify the commit - use pre-commit for validation.

95% confidence
A

Unset GIT_DIR when running git commands inside hooks: unset GIT_DIR or use env -i git .... Git sets GIT_DIR to point to the repository, which can cause commands to operate on the wrong directory. This is especially important in post-receive hooks when you need to checkout to a deployment directory. Alternatively, explicitly set --git-dir and --work-tree flags.

95% confidence
A

In hooks/post-receive: #!/bin/bash\ngit --work-tree=/var/www/app --git-dir=/srv/git/app.git checkout -f\nsudo systemctl restart nginx. Make executable: chmod +x hooks/post-receive. For sudo without password, add to sudoers: git ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx. This deploys code and restarts on every push.

95% confidence
A

Use printf for reliable hook creation:

printf '#!/bin/bash\nwhile read oldrev newrev refname; do\n  branch=${refname#refs/heads/}\n  case "$branch" in\n    main)\n      git --work-tree=/var/www/html --git-dir=/git/project checkout -f $branch\n      ;;\n    dev)\n      git --work-tree=/var/www/dev --git-dir=/git/project checkout -f $branch\n      ;;\n  esac\ndone\n' > /git/project/hooks/post-receive

Then make it executable:

chmod +x /git/project/hooks/post-receive

Verify content:

cat /git/project/hooks/post-receive

Test manually before pushing:

echo 'oldsha newsha refs/heads/main' | /git/project/hooks/post-receive
ls -la /var/www/html/  # Should show deployed files

AVOID: cat << 'EOF' heredocs - they break in automated/terminal environments.

95% confidence
A
  1. Create hook file: touch /path/to/repo.git/hooks/post-receive. 2) Make executable: chmod +x /path/to/repo.git/hooks/post-receive. 3) Set owner if needed: chown git:git /path/to/repo.git/hooks/post-receive. 4) Ensure target directories exist and are writable: mkdir -p /var/www/html && chown git:git /var/www/html (or appropriate user). 5) Test manually: echo 'old new refs/heads/main' | /path/to/repo.git/hooks/post-receive. Debug: Add set -x at start of hook to see execution. Add exec >> /tmp/post-receive.log 2>&1 to log output.
95% confidence
A

Client-side hooks: pre-commit (validate before commit), prepare-commit-msg, commit-msg, post-commit, pre-rebase, post-checkout, post-merge, pre-push. Server-side hooks: pre-receive (can reject push), update (per-branch), post-receive (after push completes). All hooks are shell scripts that must be executable. Non-zero exit from pre-* hooks aborts the operation.

95% confidence

Git Troubleshooting

8 questions
A

Steps to recover lost commits after git checkout:

  1. View reflog to find the lost commit:
    git reflog
    Entries show: HEAD@{n}: :
    Look for your commit message or the checkout that moved away from it.

  2. Verify the commit contains your changes:
    git show

  3. Recovery options (choose based on your needs):

    Option A - Create branch and merge (recommended for most cases):
    git checkout -b recovery-branch
    git checkout master
    git merge recovery-branch
    This preserves history and has better conflict resolution.

    Option B - Cherry-pick (for isolated, self-contained changes):
    git cherry-pick
    Best for small, discrete fixes. Creates a duplicate commit.

    Option C - Hard reset (to completely restore state):
    git reset --hard
    Warning: discards current uncommitted changes.

Important: Reflog entries expire after 90 days (reachable) or 30 days (unreachable) by default. Reflogs are local only - they are not shared with remotes.

95% confidence
A

Run git fsck --full to verify all objects and references. Key options: --unreachable (show orphaned objects), --dangling (show objects not in any ref), --lost-found (write dangling objects to .git/lost-found/). Exit code 0 means healthy, 1 means issues found. Use after crashes or disk errors. Combine with --strict for thorough checking.

95% confidence
A

Recreate HEAD with the correct branch reference: echo 'ref: refs/heads/main' > .git/HEAD (replace 'main' with your branch name). If you don't know the branch, check refs/heads/ for available branches. HEAD is critical - without it, git won't recognize the directory as a repository. For detached HEAD, write the commit hash directly.

95% confidence
A

Run git reflog to see HEAD history including 'lost' commits. Find the commit hash you need, then: git checkout <hash> to inspect, or git branch recovery-branch <hash> to create a branch pointing to it, or git reset --hard <hash> to restore (destroys current changes). Reflog entries expire after 90 days by default (gc.reflogExpire).

95% confidence
A

Install git-repair (available via package managers or git-annex). Run git-repair to automatically fix issues by: deleting corrupt objects, fetching missing objects from remotes, resetting branches if needed. Use --force for more aggressive repair (may rewrite history). Always backup first: tar -czf backup.tar.gz .git. It handles cases git fsck only reports.

95% confidence
A

Delete the corrupt index and rebuild it: rm .git/index && git reset or rm .git/index && git add -A. The index (.git/index) is the staging area - it can be regenerated from the working directory and HEAD. Always backup first: cp .git/index .git/index.backup. If files are missing, use git checkout HEAD -- . to restore from last commit.

95% confidence
A

Use reflog to find the branch tip: git reflog or git reflog show <branchname>. Find the commit hash of the branch tip (look for checkout or commit entries). Recreate the branch: git branch <branchname> <commit-hash>. This works because branch deletion only removes the reference - commits remain until garbage collected.

Sources
95% confidence
A

It writes dangling/unreachable objects to .git/lost-found/. Commits go to lost-found/commit/, other objects (blobs, trees) go to lost-found/other/. For blobs, actual file contents are written. Use this to recover orphaned commits or files after accidental resets. Examine contents: git show <hash> or cat .git/lost-found/other/<hash>.

95% confidence

Git Configuration

5 questions
A

To force git to use SSH password auth instead of keys, set GIT_SSH_COMMAND:

export GIT_SSH_COMMAND='ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no'
git clone git@localhost:/path/to/repo

This disables public key auth and forces password prompts.

Alternatively, configure in ~/.ssh/config:

Host localhost
    PreferredAuthentications password
    PubkeyAuthentication no
    StrictHostKeyChecking no

If password auth still fails after this, the problem is server-side (sshd_config or user password), not client-side.

95% confidence
A

Global (all repos): git config --global user.name 'Your Name' and git config --global user.email '[email protected]'. Per-repository: git config user.name 'Name' and git config user.email 'email' (run inside repo). View config: git config --list or git config user.name. Global config stored in ~/.gitconfig, local in .git/config.

95% confidence
A

Set git user name and email before committing: git config user.name 'Your Name' && git config user.email '[email protected]'. For global config (all repos): add --global flag. In scripts/automation, use: git config user.name 'Deploy Bot' && git config user.email 'deploy@localhost'. The identity is required for commits. Verify with: git config user.name && git config user.email. This error occurs when git needs to create a commit but doesn't know who to attribute it to.

95% confidence
A

For new repositories: git config --global init.defaultBranch main. This affects git init. For existing repo, rename branch: git branch -m master main. Update remote: git push -u origin main then delete old: git push origin --delete master. Update default on GitHub/GitLab through web interface.

95% confidence
A

Three levels (highest to lowest precedence): 1) Local (.git/config) - repository specific, 2) Global (~/.gitconfig) - user specific, 3) System (/etc/gitconfig) - machine-wide. Local overrides global, global overrides system. View all with sources: git config --list --show-origin. Use --local, --global, or --system flags to target specific level.

95% confidence

Git Repository Sanitization

5 questions
A

Add sensitive files to .gitignore: echo '.env' >> .gitignore && echo 'credentials.json' >> .gitignore. Use git-secrets or pre-commit hooks to scan for patterns. Set up a pre-commit hook: grep -r 'password\|secret\|api_key' --include='*' . && exit 1. Use environment variables instead of config files. Review git status before every commit.

95% confidence
A

Install: pip install git-filter-repo or brew install git-filter-repo. Remove file: git filter-repo --path <file> --invert-paths. Remove by pattern: git filter-repo --path-glob '*.log' --invert-paths. Rewrite messages: git filter-repo --message-callback 'return message.replace(b"secret", b"***")'. Faster and safer than filter-branch. Force push required after.

95% confidence
A
  1. Commit removal of sensitive file first (BFG protects HEAD). 2) Run: java -jar bfg.jar --delete-files <filename> repo.git or bfg --replace-text passwords.txt repo.git. 3) Clean: cd repo.git && git reflog expire --expire=now --all && git gc --prune=now --aggressive. 4) Force push: git push --force. Collaborators must re-clone or rebase.
95% confidence
A

After removing sensitive data, purge all references: git reflog expire --expire=now --all (remove reflog entries), git gc --prune=now --aggressive (garbage collect unreachable objects). Delete backup refs: rm -rf .git/refs/original/. Force push all branches: git push origin --force --all && git push origin --force --tags. Collaborators must re-clone.

95% confidence

SSH Server Setup

5 questions
A

Edit /etc/ssh/sshd_config and set PasswordAuthentication yes. Also check /etc/ssh/sshd_config.d/ for override files (common on Ubuntu 22.04+). Remove or comment out any PasswordAuthentication no lines. For containers/cloud servers, also check /etc/ssh/sshd_config.d/50-cloud-init.conf. After changes, restart SSH: service ssh restart or systemctl restart sshd. Verify with sshd -T | grep passwordauthentication which should show passwordauthentication yes.

95% confidence
A

Install openssh-server: apt-get update && apt-get install -y openssh-server. Create required directories: mkdir -p /var/run/sshd. Start the service: service ssh start (Debian/Ubuntu) or systemctl start sshd (systemd). Verify it's running: service ssh status or check with ss -tlnp | grep :22. The SSH server listens on port 22 by default. For containers, you may need to run /usr/sbin/sshd -D directly.

95% confidence
A

Set password interactively: passwd username then enter password twice. Set password non-interactively (scripts/automation): echo 'username:password' | chpasswd. For root user: echo 'root:mypassword' | chpasswd. Verify the user can login: su - username with the password. Also ensure the user's shell is valid (not /usr/sbin/nologin or /bin/false) by checking /etc/passwd.

95% confidence
A

Connection refused: 1) Check SSH server running: service ssh status. 2) Check listening port: ss -tlnp | grep :22. 3) Start if not running: service ssh start. Permission denied: 1) Check password authentication enabled: grep -i passwordauth /etc/ssh/sshd_config. 2) Check user exists and has valid shell: grep username /etc/passwd. 3) Check password is set: try su - username. 4) Check logs: tail /var/log/auth.log. 5) Verify with verbose SSH: ssh -v user@host. Common fixes: sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config && service ssh restart.

95% confidence
A

Check service status: service ssh status or systemctl status sshd. Check listening port: ss -tlnp | grep :22 or netstat -tlnp | grep :22. Test local connection: ssh -o BatchMode=yes -o ConnectTimeout=5 localhost echo 'SSH works'. For password auth test: sshpass -p 'password' ssh user@localhost echo 'Password auth works' (requires sshpass installed). Check logs: journalctl -u ssh -n 20 or /var/log/auth.log.

95% confidence

Git Remotes

5 questions
A

This error means the remote has commits you don't have locally. Solutions: 1) Pull first then push: git pull --rebase origin main && git push. 2) Force push if you're SURE (overwrites remote): git push --force or git push -f. 3) For new bare repos, this usually means the branch doesn't exist yet - just push: git push -u origin main. WARNING: Force push destroys remote history. For shared repos, coordinate with team. For personal/new repos, force push is safe. To allow force push in bare repo: git config receive.denyNonFastForwards false.

95% confidence
A

Push and set tracking: git push -u origin <branch-name>. The -u (--set-upstream) flag configures tracking so future push/pull work without arguments. Without tracking: git push origin <branch-name>. Push all branches: git push --all origin. Push tags: git push --tags.

95% confidence
A

git fetch downloads commits, files, and refs from remote without modifying local branches - safe to run anytime. git pull = git fetch + git merge (or rebase with --rebase). fetch is 'read-only', pull modifies your current branch. Use fetch to see what others pushed without integrating, use pull when ready to integrate changes.

95% confidence
A

Add remote: git remote add <name> <url>. Convention: 'origin' for primary remote. Example: git remote add origin https://github.com/user/repo.git. List remotes: git remote -v. Change URL: git remote set-url origin <new-url>. Remove: git remote remove <name>. Rename: git remote rename <old> <new>.

95% confidence

Advanced Git

3 questions
A

Create worktree: git worktree add ../feature-branch feature-branch (creates directory with that branch checked out). List: git worktree list. Remove: git worktree remove ../feature-branch. Each worktree is an independent working directory sharing the same .git. Cannot checkout same branch in multiple worktrees. Ideal for parallel development without stashing.

95% confidence
A

Prunes ALL unreachable objects immediately, ignoring the default 2-week grace period. Use after removing sensitive data or when certain all unreachable objects are unwanted. Warning: can lose recoverable commits if run prematurely. Normally gc.pruneExpire=2.weeks.ago protects against accidental data loss. Combine with git reflog expire --expire=now --all for complete cleanup.

95% confidence
A

Manual: git gc. Aggressive (slower but more thorough): git gc --aggressive. Auto (runs if thresholds exceeded): git gc --auto. Prune immediately: git gc --prune=now. gc packs loose objects, removes unreachable objects, compresses file revisions. Runs automatically after certain operations. Default prune keeps objects for 2 weeks.

95% confidence

Git Clean and Reset

3 questions
A

Use git clean -f to remove untracked files (force required). Options: -d includes directories, -x includes ignored files, -X removes only ignored files. Always preview first with -n (dry run): git clean -n -fd. Warning: untracked files are not in version control - deletion is permanent and cannot be undone via git.

95% confidence
A

--soft: Moves HEAD only, keeps staging area and working directory unchanged. Staged changes remain staged. --mixed (default): Moves HEAD and resets staging area, keeps working directory. Changes become unstaged. --hard: Moves HEAD, resets staging area AND working directory. All changes are discarded permanently. Use --hard with caution.

95% confidence
A

Combine reset and clean: git reset --hard HEAD && git clean -fd. This reverts all tracked files to last commit (--hard) and removes all untracked files and directories (-fd). To also remove ignored files: git clean -fdx. For resetting to a specific commit: git reset --hard <commit>. Always verify with git status afterward.

95% confidence

Git Rebase

3 questions
A

Start: git rebase -i HEAD~n (n = number of commits). In editor, change 'pick' to 'squash' (or 's') for commits to combine into previous. First commit stays 'pick'. Save and close. Edit combined commit message. Result: multiple commits become one. Use for cleaning up before merging feature branches. Never rebase published commits.

95% confidence
A

Abort (return to pre-rebase state): git rebase --abort. Continue after resolving conflicts: fix files, git add <files>, then git rebase --continue. Skip current commit: git rebase --skip (discards that commit's changes). Check status: git status shows rebase progress. Rebase state stored in .git/rebase-merge/ or .git/rebase-apply/.

95% confidence
A

Both combine commits into the previous one. 'squash' opens editor to combine commit messages - you can edit the result. 'fixup' discards the commit message, keeping only the previous commit's message. Use fixup for typo fixes or minor amendments where the commit message isn't valuable. Use squash when you want to combine meaningful messages.

95% confidence

Git Undo Operations

3 questions
A

Keep changes staged: git reset --soft HEAD~1. Keep changes unstaged: git reset --mixed HEAD~1 (or just git reset HEAD~1). This moves HEAD back one commit. For pushed commits, use git revert HEAD instead to create a new commit that undoes changes (safer for shared branches). Never reset published commits.

95% confidence
A

Using restore (Git 2.23+): git restore <file> (from index) or git restore --source=HEAD <file> (from last commit). Using checkout: git checkout -- <file> or git checkout HEAD -- <file>. All unstaged changes to that file are discarded. For staged changes, first unstage: git restore --staged <file>.

95% confidence
A

Change message only: git commit --amend -m 'New message'. Add files to last commit: stage files with git add, then git commit --amend --no-edit. Change author: git commit --amend --author='Name <email>'. Amend creates a new commit replacing the old one. Never amend pushed commits that others may have pulled.

95% confidence

Nginx Configuration

2 questions
A

Configure Nginx with multiple location blocks using alias directive:

server {
listen 8443 ssl;
ssl_certificate /etc/ssl/certs/nginx.crt;
ssl_certificate_key /etc/ssl/private/nginx.key;

# Main content at root
root /var/www/html;
index index.html;

location / {
    try_files $uri $uri/ =404;
}

# Dev content at /dev/
location /dev/ {
    alias /var/www/dev/;
    index index.html;
    try_files $uri $uri/ =404;
}

}

Key points: 1) Use alias (not root) for /dev/ - alias replaces the matched location, root appends to it. 2) The trailing slashes matter: location /dev/ with alias /var/www/dev/. 3) Create both directories: mkdir -p /var/www/html /var/www/dev. 4) Reload Nginx after changes: nginx -t && nginx -s reload.

Sources
95% confidence
A
  1. Generate self-signed cert: openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx.key -out /etc/ssl/certs/nginx.crt -subj '/CN=localhost'. 2) Nginx config for custom port (e.g., 8443):
    server {
    listen 8443 ssl;
    ssl_certificate /etc/ssl/certs/nginx.crt;
    ssl_certificate_key /etc/ssl/private/nginx.key;
    root /var/www/html;
    index index.html;
    location / { try_files $uri $uri/ =404; }
    }
  2. Test config: nginx -t. 4) Reload: nginx -s reload or service nginx reload. 5) Test: curl -k https://localhost:8443 (-k ignores self-signed cert warning).
Sources
95% confidence

Git Web Interface

2 questions
A

Install: gitweb and fcgiwrap. Nginx config: location /gitweb { include fastcgi_params; fastcgi_param GITWEB_CONFIG /etc/gitweb.conf; fastcgi_pass unix:/var/run/fcgiwrap.socket; }. In /etc/gitweb.conf: $projectroot = '/var/lib/git';. Enable fcgiwrap service. Ensure nginx user can read git repos. Access via http://server/gitweb.

95% confidence
A

Install: cgit, fcgiwrap. Nginx config: location /cgit { include fastcgi_params; fastcgi_param SCRIPT_FILENAME /usr/share/webapps/cgit/cgit.cgi; fastcgi_param CGIT_CONFIG /etc/cgitrc; fastcgi_pass unix:/var/run/fcgiwrap.socket; }. /etc/cgitrc: scan-path=/srv/git. Static files: serve cgit.css and cgit.png directly. cgit is faster than gitweb with built-in caching.

95% confidence

Git Plumbing

2 questions
A

Create/update ref: git update-ref refs/heads/branch <commit>. Delete ref: git update-ref -d refs/heads/branch. Safe update (verify old value): git update-ref refs/heads/branch <new> <old>. Create tag: git update-ref refs/tags/v1.0 <commit>. Low-level plumbing command - use porcelain commands (branch, tag) when possible.

95% confidence
A

Read current branch: git symbolic-ref HEAD returns 'refs/heads/main'. Set HEAD to branch: git symbolic-ref HEAD refs/heads/feature. Check if HEAD is symbolic: git symbolic-ref -q HEAD (exits 1 if detached). Short name: git symbolic-ref --short HEAD returns 'main'. Used by scripts to programmatically manipulate branch references.

95% confidence

SSH Configuration

2 questions
A

When a task specifically requires SSH password authentication, do NOT set up SSH keys as a workaround because:

  1. The verification test expects password prompts - if SSH keys bypass the prompt, the test fails
  2. Password auth is often required for specific security/audit reasons
  3. SSH keys change the authentication flow completely

If password auth isn't working, fix it properly:

  • Check sshd_config: PasswordAuthentication yes
  • Check for override files in /etc/ssh/sshd_config.d/
  • Ensure user password is set: echo 'user:password' | chpasswd
  • Restart sshd: service ssh restart
  • Test explicitly: ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@localhost

DO NOT: Generate SSH keys, add to authorized_keys, or use ssh-agent as workarounds when password auth is the requirement.

95% confidence
A

Test SSH password auth BEFORE setting up git to avoid wasting time:

  1. Ensure sshd is running: service ssh start
  2. Test with explicit password prompt:
    ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no git@localhost echo "Password auth works"
  3. When prompted, enter the password. If it works, you'll see "Password auth works".

If it fails with "Permission denied", check:

  • Password was set correctly: echo 'git:password' | chpasswd
  • sshd_config has PasswordAuthentication yes
  • Restart sshd after config changes: service ssh restart
  • Check for override files: ls /etc/ssh/sshd_config.d/ and ensure none disable password auth

IMPORTANT: Do NOT set up SSH keys as a workaround if password auth is specifically required. The -o PubkeyAuthentication=no flag forces password auth for testing.

95% confidence

Merge Conflicts

2 questions
A

<<<<<<< HEAD marks start of your current branch's version. ======= separates the two versions. >>>>>>> branch-name marks end of incoming branch's version. Everything between <<<<<<< and ======= is your code, between ======= and >>>>>>> is their code. Edit file to keep desired content and remove all markers before staging.

95% confidence
A
  1. git status shows conflicted files. 2) Open files, find conflict markers (<<<<<<<, =======, >>>>>>>). 3) Edit to resolve - keep desired code, remove markers. 4) Stage resolved files: git add <file>. 5) Complete merge: git commit. Abort if needed: git merge --abort. Use git mergetool for visual resolution.
95% confidence

Git Diff

2 questions
A

Two dots (A..B): Shows changes between tip of A and tip of B - direct comparison of endpoints. Three dots (A...B): Shows changes on B since it diverged from A - compares B to merge-base of A and B. Three dots is useful for reviewing what a branch adds, ignoring changes on the base branch since branching.

95% confidence
A

Unstaged changes: git diff. Staged changes: git diff --staged (or --cached). All uncommitted: git diff HEAD. Between commits: git diff <commit1> <commit2>. Between branches: git diff branch1..branch2. Specific file: git diff -- <file>. Stats only: git diff --stat. Names only: git diff --name-only.

95% confidence

Git Debugging

2 questions
A

Start: git bisect start. Mark current as bad: git bisect bad. Mark known good commit: git bisect good <commit>. Git checkouts middle commit. Test and mark: git bisect good or git bisect bad. Repeat until found. End: git bisect reset. Automate: git bisect run ./test-script.sh (script exits 0 for good, 1 for bad).

95% confidence
A

Basic: git blame <file>. Shows commit hash, author, date, line number, and content for each line. Ignore whitespace: git blame -w. Show original commit for moved/copied lines: git blame -C. Specific lines: git blame -L 10,20 <file>. Date format: git blame --date=short. Skip specific revisions: git blame --ignore-rev <commit>.

95% confidence

Git Log

1 question
A

Basic: git log. One line per commit: git log --oneline. With graph: git log --graph --oneline --all. Specific file: git log -- <file>. By author: git log --author='Name'. Date range: git log --since='2024-01-01' --until='2024-12-31'. Search message: git log --grep='fix'. Show changes: git log -p. Limit: git log -n 10.

95% confidence

Git Deployment

1 question
A

Use EXACT plain text content, NOT HTML. When creating files for git branch deployments:

CORRECT - Plain text:

echo 'main branch content' > index.html
echo 'dev branch content' > index.html

WRONG - HTML tags:

echo '<html><body>Main Branch</body></html>' > index.html  # WRONG!
echo '<h1>Dev Content</h1>' > index.html  # WRONG!

Why plain text matters:

  1. Tests often check for EXACT content matches
  2. curl https://localhost/index.html should return exactly the content you put in
  3. HTML wrappers break string comparison tests

Verification pattern:

git push origin main
sleep 1
curl -sk https://localhost:8443/index.html
# Should output exactly: main branch content

CRITICAL: If a task doesn't specify HTML, use simple plain text. The test will compare the EXACT response body.

95% confidence

Git Authentication

1 question

Git Basics

1 question
A

Create new repo: git init in existing directory, or git init <directory> to create directory and init. Creates .git subdirectory. Add files: git add .. First commit: git commit -m 'Initial commit'. Set remote: git remote add origin <url>. Push: git push -u origin main. For bare repo: git init --bare.

95% confidence

Web Server Setup

1 question
A

Use echo with redirection: echo 'Hello World' > /var/www/html/index.html. For multi-line content, use heredoc: cat > /var/www/html/index.html << 'EOF' Your content here EOF. Ensure directory exists first: mkdir -p /var/www/html. Set proper permissions: chmod 644 /var/www/html/index.html. Verify: cat /var/www/html/index.html. IMPORTANT: Use EXACT content required - don't add extra HTML tags, doctype, or formatting unless specifically requested.

Sources
95% confidence

Git Internals

1 question
A

Key contents: HEAD (current branch ref), config (local config), objects/ (all data - blobs, trees, commits), refs/ (branches and tags), refs/heads/ (local branches), refs/remotes/ (remote tracking), refs/tags/ (tags), index (staging area), hooks/ (hook scripts), logs/ (reflog). Bare repos have same structure but no working directory.

95% confidence

Git Tags

1 question
A

Lightweight tag: git tag v1.0. Annotated tag (recommended): git tag -a v1.0 -m 'Version 1.0 release'. Tag specific commit: git tag -a v1.0 <commit> -m 'message'. List tags: git tag or git tag -l 'v1.*'. Push tag: git push origin v1.0. Push all tags: git push origin --tags. Delete: git tag -d v1.0.

95% confidence