rick
rick

Reputation: 53

Git command in Powershell: "git log $strVar" does not work

In PowerShell the git command below doesn't work

$strVar = "--graph --oneline"
git log $strVar

It returns: fatal: unrecognized argument: --graph --oneline. Why doesn't it work?

I noticed that the space has something to do with the my problem because this will work:

git log "--oneline"

But this doesn't work:

git log "--oneline " 

Upvotes: 1

Views: 350

Answers (1)

phuclv
phuclv

Reputation: 41764

git log "--oneline " doesn't work because git receives --oneline with a trailing space as a single argument. Same to your git log $strVar where git receives $strVar as a parameter. PowerShell works on objects and not strings so in PowerShell you typically don't save parameters in a string like that and use arrays instead, then run the command with the call operator &

$params = "--graph", "--oneline" # Or '@("--graph", "--oneline")'
# '@()' denotes an array, '+' is an array concatenation
& git (@("log") + $params)
# Alternative way, the comma operator converts the operand to array
& git (,"log" + $params)

You can also use Invoke-Expression for parameters in a single string, but only when the whole command line is simple because if there are special characters then you'll need some escaping

$params = "--graph --oneline"
Invoke-Expression ("git log " + $params)
iex "git log $params" # Alias of Invoke-Expression

Another solution is to use Start-Process

Start-Process -FilePath git -ArgumentList (@("log") + $params)
saps git (,"log" + $params) # Alias

Upvotes: 1

Related Questions