# How can I implement cd (change dir) command in Ruby?

**URL:** <https://www.ruby-forum.com/t/how-can-i-implement-cd-change-dir-command-in-ruby/107435>\
**Category:** Ruby\
**Created:** [June 21, 2007, 7:56pm UTC](https://www.ruby-forum.com/t/how-can-i-implement-cd-change-dir-command-in-ruby/107435 "2007-06-21T19:56:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ssk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/82dd89/32.png) [@ssk](https://www.ruby-forum.com/u/ssk)\
**Post date:** [June 21, 2007, 7:56pm UTC](https://www.ruby-forum.com/t/how-can-i-implement-cd-change-dir-command-in-ruby/107435/1 "2007-06-21T19:56:19Z")

</div>

Hi,

This question is rather out of curiosity than practical.

Let’s say I want to make a script which is equivalent to cd command in  
Linux.  
Is it possible?

Usage:

~$ ruby mycd.rb /temp  
/temp$ \<- current dir has been changed after the script ran.

system(“cd #{ARGV[0]}”) didn’t work.

Thanks.

Sam

---

<div class="post-metadata">

**Author:** ![ssk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/82dd89/32.png) [@ssk](https://www.ruby-forum.com/u/ssk)\
**Post date:** [June 21, 2007, 8:05pm UTC](https://www.ruby-forum.com/t/how-can-i-implement-cd-change-dir-command-in-ruby/107435/2 "2007-06-21T20:05:20Z")

</div>

On 6/21/07, Sam K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hi,
> 
> This question is rather out of curiosity than practical.
> 
> Let’s say I want to make a script which is equivalent to cd command in  
> Linux.  
> Is it possible?

Only if your shell is done in Ruby as well. chdir(2) changes the  
directory for the process which invokes it. cd is a shell built-in,  
one which has no analog in /bin.

> system(“cd #{ARGV[0]}”) didn’t work.

That will spawn a new process running /bin/sh. That shell will change  
its directory and then exit. afaik what you want is not possible  
without resorting to (ugly) trickery.

Hope this helps.
