Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec the cd command in a ruby script

Tags:

ruby

I'd like to change the pwd of the current shell from within a ruby script. So:

> pwd
/tmp
> ruby cdscript.rb
> pwd
/usr/bin

This is the code I have right now:

exec('cd /usr/bin')

Unfortunately, cd is a builtin command. So:

`exec': No such file or directory - cd (Errno:ENOENT)

Any workaround for this?


No way to get it working in ruby itself, so I switched gears. I modified the script to output the target directory path and then defined a function in .bashrc that would pass the arguments through the script and then cd to the right directory. Not self-contained as I would have hoped, but it did the job.

Thanks for the replies, folks.

like image 815
Joe Mastey Avatar asked Aug 04 '10 22:08

Joe Mastey


People also ask

Can we use cd command in shell script?

The cd command, also known as chdir (change directory), is a command-line shell command used to change the current working directory in various operating systems. It can be used in shell scripts and batch files.

How do I run a shell script in Ruby?

Create configurations for script files and select Shell Script. Under Execute, select the Script file option. Specify the path to the script file and options that you want to pass to the script when it is launched.

How do I change directory in Ruby?

chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.


1 Answers

Dir.chdir("/usr/bin") will change the pwd within the ruby script, but that won't change the shell's PWD as the script is executed in a child process.

like image 94
Vinko Vrsalovic Avatar answered Oct 16 '22 02:10

Vinko Vrsalovic