Docker镜像执行Git克隆报错‘fatal: Not a git repository’求助
Let's break down what's going wrong here and fix it step by step:
1. Incorrect Directory Check
Your script uses -f /folder/.git to verify the repository exists—but .git is a directory, not a regular file. The -f flag only checks for ordinary files, so this condition will always evaluate to false, even if the repository is already present. That means your script skips the git clone step entirely and jumps straight to git pull.
2. Reversed Logic Flow
Even if the check worked, your logic is backwards: you're trying to clone only when the .git directory exists, and pull when it doesn't. That's the opposite of what you need—pull makes sense only when the repository is already set up, while clone is for when it's missing.
Corrected update.sh Script
Here's the fixed version that addresses both issues:
#!/bin/bash # Check if the .git directory exists (validating it's a git repo) if [ -d "/folder/.git" ]; then # If repo exists, pull the latest changes git -C /folder pull else # If no repo exists, clone it to the target folder git clone https://TOKEN@github.com/company/project.git /folder fi
Extra Robustness (Optional)
If there's a chance /folder exists but isn't a git repository (e.g., leftover files from a failed run), add cleanup logic to avoid clone errors:
#!/bin/bash if [ -d "/folder/.git" ]; then git -C /folder pull elif [ -d "/folder" ]; then # Folder exists but isn't a repo—clean it up first rm -rf /folder git clone https://TOKEN@github.com/company/project.git /folder else # Folder doesn't exist at all—clone directly git clone https://TOKEN@github.com/company/project.git /folder fi
Dockerfile Quick Tip
Don't forget to ensure your script has executable permissions in the image. Add these lines to your Dockerfile:
COPY update.sh /update.sh RUN chmod +x /update.sh CMD [ "/update.sh" ]
This should resolve the "Not a git repository" error and make your clone/pull logic work as intended.
内容的提问来源于stack exchange,提问作者Vitalii Vasylenko

