3

Kind of a stupid question, but I'm not able to run git commands from a ruby script. Do I need to be sourcing something?

Simple example of script:

   checkout = %x("/usr/bin/git version")
puts checkout

Output:

sh: /usr/bin/git version: No such file or directory

If I run the command from the cmd line it works:

git version 1.7.9.5

Any input appreciated. Thanks.

2
  • Use which git to figure out where your git actually resides. Commented Apr 3, 2014 at 14:28
  • This is a bit late, but the reason for the error is the quotes inside your %x, had you done %x(/usr/bin/git version) instead then you would have gotten the git version Commented Jul 13, 2022 at 23:38

1 Answer 1

11

you can use Kernel#system or Kernel#exec or this quotes ``:

  $> irb
  => `git status`
  => "# On branch develop\nnothing to commit, working directory clean\n"
  => system('git version')
  => git version 1.8.3.4 (Apple Git-47)
  => exec('git version')
  => git version 1.8.3.4 (Apple Git-47)

in script:

#!/usr/bin/env ruby
puts system('git version')
puts `git version`
puts exec('git version')

output:

git version 1.8.3.4 (Apple Git-47)
true
git version 1.8.3.4 (Apple Git-47)
git version 1.8.3.4 (Apple Git-47)
Sign up to request clarification or add additional context in comments.

3 Comments

Nah, I need to run git commands on arguments I pass to a script. irb won't work for me here...
@user797963 IRB is just being used as an example, anything you write in IRB can be copy-pasted into a Ruby script and run from there. It's identical.
Be warned that exec will not return. If you plan to do anything with the results of your git call, you need to use a different method like system or the backticks.

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.