Windows命令行Git变量语法修正:如何让远程仓库URL解析生效?
Windows pwsh环境下Git远程仓库配置错误修复
问题场景
在windows-latest GitHub Runner的pwsh shell中执行以下命令时,Git无法识别远程仓库URL:
set repoWithToken="https://"$GIT_PAT"@github.com/accountName/repoName.git" git init git remote add origin %repoWithToken%
报错信息
fatal: '%repoWithToken%' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Error: Process completed with exit code 1.
错误原因
- 变量引用语法错误:pwsh(PowerShell)中引用变量需使用
$变量名,而非CMD风格的%变量名%,原命令里的%repoWithToken%未被正确解析。 - 字符串拼接与赋值格式错误:原
set命令的赋值方式不符合PowerShell语法,导致变量repoWithToken未正确存储拼接后的URL。
修复后的命令
方式一:PowerShell原生简单语法
直接用PowerShell变量赋值规则,字符串内可直接嵌入环境变量:
$repoWithToken = "https://$GIT_PAT@github.com/accountName/repoName.git" git init git remote add origin $repoWithToken
方式二:CMD兼容语法(若偏好传统Windows命令格式)
调整set命令的引号位置,统一用CMD风格变量引用:
set "repoWithToken=https://%GIT_PAT%@github.com/accountName/repoName.git" git init git remote add origin %repoWithToken%
说明
- 两种方式都能正确拼接包含GitHub PAT的仓库URL,确保Git能识别远程仓库地址。
- 若
$GIT_PAT是GitHub Runner提供的环境变量,在PowerShell中也可写为$env:GIT_PAT,效果一致。
内容的提问来源于stack exchange,提问作者CodeMed
相关产品推荐
相关产品推荐

