Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily change current directory in Rake

Tags:

ruby

rake

fabric

I would like to run multiple commands need to be (or is easier to be) in another directory, then once they're done, return back to the previous working directory.

I'm envisioning something similar to Fabric's with cd(path):, e.g.:

cd('.git') do
   File.unlink('config')
end

Is there an inbuilt way of doing this in Rake, or should I be writing a custom method that accepts a block, etc.?

like image 777
gak Avatar asked May 14 '13 01:05

gak


People also ask

How do I change the working directory in shell?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

How do I change the working directory in Linux?

To change to your home directory, type cd and press [Enter]. To change to a subdirectory, type cd, a space, and the name of the subdirectory (e.g., cd Documents) and then press [Enter]. To change to the current working directory's parent directory, type cd followed by a space and two periods and then press [Enter].

What is the use of Rakefile?

rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other. You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks.

Which shell command can you use to change the current working directory to the parent of that directory?

In the shell, the command cd - is a special case that changes the current working directory to the previous working directory by exchanging the values of the variables PWD and OLDPWD. Note: Repeating this command toggles the current working directory between the current and the previous working directory.


1 Answers

It is simply the inbuilt Dir#chdir call:

Dir.chdir('.git') do
  File.unlink('config')
end

Excerpt from the docs:

If a block is given, it is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits.

like image 70
gak Avatar answered Sep 28 '22 03:09

gak