Ruby run shell command in a specific directory
You can use the block-version of Dir.chdir
. Inside the block you are in the requested directory, after the Block you are still in the previous directory:
Dir.chdir('mydir'){
%x[#{cmd}]
}
How do I run commands in a given directory in Ruby?
try: Dir.chdir
method. Reference: http://www.ruby-doc.org/core-2.1.0/Dir.html#method-c-chdir
Dir.chdir(directory) do
run("bower install", capture: true, verbose: false)
end
The above example code will change to the directory represented by the directory
variable, and then run whatever commands you pass to this block.
Running shell commands from a specific directory
Using Bash commands like pushd
in Ruby is pointless, because those commands affect Bash's internal state of the Bash interpreter, and when you Run a shell command from Ruby using backticks or system
, it creates a new subprocess, runs the command, and then closes that subprocess.
That means that even if you somehow manage to run pushd
as a Bash command from Ruby, what will happen is that the the Bash subprocess will start, push the directory to the directory stack, and then exit. The changes you've made to the directory stack will be erased with all the other subprocess' data - and the next time you use a shell command you won't be at that directory.
You are scripting in Ruby, not in Bash - internal Bash commands have no meaning here, so you need to use the Ruby equivalents. For example, instead of writing:
system 'pushd /tmp'
system 'touch file_in_tmp'
system 'popd'
Which wouldn't work, what you want to do is:
Dir.chdir '/tmp' do
system 'touch file_in_tmp'
end
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
Call shell skript with specific working directory from R
As system2
uses shQuote we can only use system()
and as already pointed out by @Dirk you can then use
system("cd ./sub && sh script.sh")
Related Topics
Rails4 Unknown Encoding Name - Cp720
String Interpolation in Ruby Doesn't Work
How to Use Define_Method to Create Class Methods
Fibonacci Sequence in Ruby (Recursion)
Controller Spec Unknown Keyword: Id
How to Get the Name of a Ruby Class
How to Remove Lines of Data in the Middle of a Text File with Ruby
Why Do I Get a "Permission Denied" Error While Installing a Gem
Undefined Method Raise_In_Transactional_Callbacks=' for Activerecord::Base:Class (Nomethoderror)
Nomethoderror When Trying to Invoke Helper Method from Rails Controller
How to Remove the Bom from a Utf-8 Encoded File
Read and Write Yaml Files Without Destroying Anchors and Aliases