I have some code in a function like so:

  let branch = substitute(system('git rev-list -1 HEAD'), '\n', '', 'g')
  let num_branches = system('echo `git branch --contains '.branch.'` | wc -l')
  if num_branches == 1
    branch = system('git branch --contains '.branch.' | cut -c3-') 

But branch is not overridden like I would expect. How do I reassign branch?

  • you should rather explain what exactly you are trying to achieve here. Note: backticks are most likely wrong here. Commented Sep 7, 2022 at 6:49
  • I'm trying to get the current git commit, and get the name of the branch associated with it if there is only one.
    – Jin
    Commented Sep 7, 2022 at 6:58
  • so have you tried: system('git branch --contains ' .. branch .. ' | wc -l') ? Commented Sep 7, 2022 at 9:14
  • 1
    Reassigning is done with let in vimscript prior to vim9script
    – D. Ben Knoble
    Commented Sep 7, 2022 at 15:00
  • @ChristianBrabandt yes I tried system('git branch --contains ' .. branch .. ' | wc -l') and it goes inside the if block. Will try let.
    – Jin
    Commented Sep 7, 2022 at 23:28

1 Answer 1


The system() return includes a trailing newline:

:let ls = system('ls | wc -l')
:echo '|' .. ls .. '|'
Press ENTER or type command to continue

You can use ->trim() to remove newlines. Also, the command is needlessly complex: git branch already outputs text, so no need for echo and backticks here.

You're also missing a let inside the if check; you always need to use let to assign variables.

It's generally a good idea to use shellescape() on variables you use inside system(), so it works when variables contain special shell characters. I prefer to use printf() for this, but you can use string concatenation with .. too.

Putting it all together:

let branch       = system('git rev-list -1 HEAD')->trim()
let num_branches = system(printf('git branch --contains %s | wc -l', branch->shellescape())->trim()
if num_branches == 1
    let branch = system(printf('git branch --contains %s | cut -c3-', branch->shellescape()))->trim()

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.