1

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 " 
3
  • It's definitely a powershell thing. Unix-style shells will do word splitting on unquoted arguments here. Commented Nov 25, 2021 at 5:55
  • I think so too. Any idea how to fix it? Commented Nov 29, 2021 at 6:40
  • No, I haven't used Powershell. I did some google searching and there's a whole bunch of rules about splitting but I don't have Powershell either and cannot experiment with them. Commented Nov 29, 2021 at 7:18

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This really helped me out, thanks you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.