CodeMed
CodeMed

Reputation: 9191

Windows command line variable in Git command

What specific syntax needs to be changed in the windows command line commands below in order for git remote add origin %repoWithToken% to resolve to the intended valid URL?

COMMANDS THAT ARE FAILING:

The following commands are run in a pwsh shell on a windows-latest GitHub runner.

set repoWithToken="https://"$GIT_PAT"@github.com/accountName/repoName.git"
git init
git remote add origin %repoWithToken%

ERROR MESSAGE:

The following error message is given by the GitHub windows-latest runner when the above code is run:

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.

The answer can just be simple windows command line command. No need for any fancy PowerShell.

Also, $GIT_PAT is correct GitHub syntax, though it is possible that the concatenation in set repoWithToken="https://"$GIT_PAT"@github.com/accountName/repoName.git" might need to be done differently in the code above. This is in the process of being translated from Bash.

Upvotes: 0

Views: 159

Answers (1)

mklement0
mklement0

Reputation: 437698

Building on Olaf's helpful comments:

  • set <varName>=<value is used in cmd.exe for assigning variables; while in PowerShell set is a built-in alias for Set-Variable, the latter has very different syntax.

    • More importantly, its use is rarely needed, because variables are assigned as $<varName> = <value>

    • PowerShell uses the same syntax on setting and getting variable values, $<varName>; thus, after having assigned to a variable named repoWithToken with $repoWithToken = <value>, you also refer to its value later with $repoWithToken (by contrast, %repoWithToken% is again cmd.exe syntax).

  • Assuming that GIT_PAT is the name of an environment variable, you must refer to it as $env:GIT_PAT in PowerShell variable (with explicit name delineation: ${env:GIT_PAT})

  • Unlike Bash (and POSIX-compatible shells in general), PowerShell only allows you to compose a single string from a mix of quoted and unquoted tokens if the first token is unquoted.

    • Something like "https://"$GIT_PAT"@github.com/accountName/repoName.git" therefore doesn't work as a single string argument, because its first token is quoted, causing PowerShell to break it into two arguments in this case.

    • Since string interpolation is needed here in order to replace ${env:GIT_PAT} with its value, simply enclose the entire value in "...", i.e. make it an expandable string

Therefore:

$repoWithToken = "https://${env:GIT_PAT}@github.com/accountName/repoName.git"
git init
git remote add origin $repoWithToken

Upvotes: 1

Related Questions