How to execute Windows CLI commands in Ruby?
`"C:\Documents and Settings\test.exe"`
or
`exec "C:\Documents and Settings\test.exe"`
or whatever in qoutes
How can I run a command line command from within a ruby file?
cmd = "ls > somefile.txt"
system( cmd )
or even just simply
system( "ls" )
Thus, you can use system.
Execute basic windows commands
You should try with whoami
instead of username
:
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
my_username = shell.ShellExecute('cmd.exe', 'whoami', '', 'open', 0)
puts my_username
You can't use ShellExecute()
because it doesn't let you access the output of the command your run which is what you want. See Using ShellExecuteEx and capturing standard in/out/err for more informations about that point.
I would simply use puts ENV['USERNAME']
which works like a charm. (Or any command given by Ilia Aptsiauri in his answer)
How to call shell commands from Ruby
This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.
First, note that when Ruby calls out to a shell, it typically calls /bin/sh
, not Bash. Some Bash syntax is not supported by /bin/sh
on all systems.
Here are ways to execute a shell script:
cmd = "echo 'hi'" # Sample string that can be used
Kernel#`
, commonly called backticks –`cmd`
This is like many other languages, including Bash, PHP, and Perl.
Returns the result (i.e. standard output) of the shell command.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-60
value = `echo 'hi'`
value = `#{cmd}`Built-in syntax,
%x( cmd )
Following the
x
character is a delimiter, which can be any character.
If the delimiter is one of the characters(
,[
,{
, or<
,
the literal consists of the characters up to the matching closing delimiter,
taking account of nested delimiter pairs. For all other delimiters, the
literal comprises the characters up to the next occurrence of the
delimiter character. String interpolation#{ ... }
is allowed.Returns the result (i.e. standard output) of the shell command, just like the backticks.
Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings
value = %x( echo 'hi' )
value = %x[ #{cmd} ]Kernel#system
Executes the given command in a subshell.
Returns
true
if the command was found and run successfully,false
otherwise.Docs: http://ruby-doc.org/core/Kernel.html#method-i-system
wasGood = system( "echo 'hi'" )
wasGood = system( cmd )Kernel#exec
Replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec
exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached because of the line above
Here's some extra advice:$?
, which is the same as $CHILD_STATUS
, accesses the status of the last system executed command if you use the backticks, system()
or %x{}
.
You can then access the exitstatus
and pid
properties:
$?.exitstatus
For more reading see:
- http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands
- http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html
- http://tech.natemurray.com/2007/03/ruby-shell-commands.html
Ruby - Calling commands and interact with shell in Windows environment
Seems this is working under Windows too
pipe = IO.popen('your.exe', 'w+', :err => [:child, :out])
@pipe.each_line do |line|
if /pattern matching question/ =~ line
break
end
end
pipe.puts('Yes')
# another test can be here
pipe.close
Wise to use with https://ruby-doc.com/stdlib/libdoc/timeout/rdoc/Timeout.html
Run command in command prompt from Ruby application
Ruby has several ways to 'shell out', and there is an in-depth post here on SO about it:
Calling shell commands from Ruby
Running cmd scripts from a ruby file?
Ruby will execute anything you put in backticks ` in your associated shell.
so if you type
test = `ipconfig`
puts test
test should now have stored in it the data from the cmd call ipconfig
EDIT
You can also use the System(..)
call in Ruby to execute commands
How does this Ruby command line work? Seemingly running a CMD script with Ruby
From man ruby
:
-x[directory]
Tells Ruby that the script is embedded in a message. Leading garbage will be discarded until the first line that starts with#!
and contains the string,ruby
Any meaningful switches on that line
will be applied. The end of the script must be specified with either
EOF ^D ( control-D ^Z ( control-Z or the reserved word__END__
If the
directory name is specified, Ruby will switch to that directory before
executing script.
Which means the ridk.cmd
has embedded ruby code.
The directory
is optional, as indicated by both the square brackets around the name and the description. If provided, it should be directly after -x
without any space, which effectively allows it to be an optional argument.
Related Topics
What Does ["String"].Pack('H*') Mean
Rails 3 - How to Set Start Date to Date_Select Method
Travis Ci: Fatal: Role Does Not Exist
Add a CSS Class to <%= F.Submit %>
Rails Routes: Wrong Singular for Resources
Splitting Routes File into Multiple Files
Access Current Git Commit Number from Within Heroku App
How to Ensure Ruby Gems Are Installed in Right Place to Be Executed by Bundler
Method for Padding an Array in Ruby
Rails ( Set_No_Cache Method) Cannot Disable Browser Caching in Safari and Opera
Select Checkbox Pass Array in Ruby on Rails
Declaring an Integer Range with Step != 1 in Ruby
Adding a Background Image in Ruby on Rails 2 in CSS
Your Ruby Version Is 2.1.0, But Your Gemfile Specified 2.0.0