exec the cd command in a ruby script
As other answers already pointed out, you can change the pwd inside your ruby script, but it only affects the child process (your ruby script). A parent process' pwd cannot be changed from a child process.
One workaround could be, to have the script output the shell command(s) to execute and call it in backticks (i.e. the shell executes the script and takes its output as commands to execute)
myscript.rb:
# … fancy code to build somepath …
puts "cd #{somepath}"
to call it:
`ruby myscript.rb`
make it a simple command by using an alias:
alias myscript='`ruby /path/to/myscript.rb`'
Unfortunately, this way you can't have your script output text to the user since any text the script outputs is executed by the shell (though there are more workarounds to this as well).
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}]
}
Change Directory with Ruby (with side effects?)
No, it is not possible.
In fact, no child process can change the current working directory of its parent process.
When you execute a script (or any program) from your command shell you are actually doing a "fork/exec" pair, which means you create a "child process" which is separate from your shell "parent process" in many ways. The child can make changes to its own environment but cannot (typically) change the parent environment.
How do I use backticks to change directories?
When you run shell commands using the tick marks, they will be run in a child process that can not change the working directory of the parent.
If you link the cd
command with another command, you will see it work, but only effecting the child process:
`cd / && ls`
To change the working directory of the parent process use the Ruby command Dir.chdir([string])
:
Dir.chdir("/")
Relevant information can be found in this post:
"exec the cd command in a ruby script"
Related Topics
What Orm to Use in One Process Multiple Db Connections Sinatra Application
How to Ssh Interactive Session
Ruby Regex to Capture Everything Between Two Strings (Inclusive)
How to Test Whether a String Would Match a Glob in Ruby
Unexpected Value of _Callee_ When Including a Module - Is This a Ruby Bug
Ruby: Automatically Set Instance Variable as Method Argument
What Does a Single Splat/Asterisk in a Ruby Argument List Mean
Ruby + Tk Command Binding - Scope Issue
How to Install "Readline" for Rails Console
Ruby: Mass Initializing Instance Variables
What's the Difference Between the Ruby Irb Prompt Modes
Performing a "Fast-Forward" Merge with Rugged
Minitest, Test::Unit, and Rails
Ruby Equivalent for Python's For/Else