Ruby Interactive Shell Commands

Ruby interactive shell commands

Original: https://stackoverflow.com/a/6488335/2724079

This can also be accomplished with IO.expect

require 'pty'
require 'expect'

PTY.spawn("play new calimero") do |reader, writer|
reader.expect(/What is the application name/)
writer.puts("\n")
end

This waits for the spawned process to display "What is the application name" and when it sees that prints a defined string (new line).

Launch interactive Bash shell in Ruby script, with initial command

Change the working directory of the Ruby script first, so that bash inherits the correct working directory.

curr_dir = Dir.pwd
Dir.chdir("#{Dir.home}/src/devops")
system "/bin/bash"
Dir.chdir(curr_dir) # Restore the original working directory if desired

Oh, this is probably far better (you can probably guess how little familiarity I have with Ruby):

system("/bin/bash", :chdir=>"#{Dir.home}/src/devops")

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
  1. 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}`
  2. 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} ]
  3. 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 )
  4. 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

Ruby open interactive sub process within the shell

What is wrong with system for this case?

  • The exec ruby command replaces the running process, so it will not return to your code.
  • The Open3 library is used when you want to capture stdout and stderr.

Isn't this what you are looking for?

puts "here"
system "cfdisk"
puts 'there'

If you have some screen related issues, this is another issue that you might be able to resolve with different TERM value in the environment variable.

How to run a Ruby script in interactive mode

No it is not. Local variables are scoped within the file.

If you want to bruce force, you can read the file as a string and eval it in the binding of the root environment of irb.

Is there a way to get the interactive ruby shell after running a script?

IRB is the interactive shell so irb -r _path_to_file_

irb --help
Usage: irb.rb [options] [programfile] [arguments]
-f Suppress read of ~/.irbrc
-m Bc mode (load mathn, fraction or matrix are available)
-d Set $DEBUG to true (same as `ruby -d')
-r load-module Same as `ruby -r'
-I path Specify $LOAD_PATH directory
-U Same as `ruby -U`
-E enc Same as `ruby -E`
-w Same as `ruby -w`
-W[level=2] Same as `ruby -W`
--inspect Use `inspect' for output (default except for bc mode)
--noinspect Don't use inspect for output
--readline Use Readline extension module
--noreadline Don't use Readline extension module
--prompt prompt-mode
--prompt-mode prompt-mode
Switch prompt mode. Pre-defined prompt modes are
`default', `simple', `xmp' and `inf-ruby'
--inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
Suppresses --readline.
--simple-prompt Simple prompt mode
--noprompt No prompt mode
--tracer Display trace for each execution of commands.
--back-trace-limit n
Display backtrace top n and tail n. The default
value is 16.
--irb_debug n Set internal debug level to n (not for popular use)
-v, --version Print the version of irb

I dont know why yours didn't but here are all the options.

How can a Ruby script detect if it was triggered by an interactive shell?

Check if STDIN is a "TTY" (literally meaning teletypewriter) with IO#isatty.

$ ruby -e 'puts STDIN.isatty'
true
$ echo "no" | ruby -e 'puts STDIN.isatty'
false


Related Topics



Leave a reply



Submit