Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run "pushd" using backticks?

Tags:

ruby

How do you run pushd and popd using backticks?

Whenever I run pushd /tmp in backticks I get an error:

"No such file or directory - pushd /tmp"
like image 986
Leonard Teo Avatar asked Aug 31 '26 21:08

Leonard Teo


1 Answers

Ruby shell-outs (backticks) each run in a new subshell, so it doesn't work perhaps in the way that you are thinking:

a = `pwd`
`cd '/tmp'`
b = `pwd`
b == a         # => true
b == "/tmp"    # => false

Also, are you sure pushd works in your shell? Maybe look at using ruby's system or popen3 if you want something more useful than the backtick syntax.

Dir#chdir accepts a block. Here's an example from the docs if all you need is to run some commands in a directory then change back:

Dir.chdir("/var/spool/mail")
puts Dir.pwd
Dir.chdir("/tmp") do
  puts Dir.pwd
  Dir.chdir("/usr") do
    puts Dir.pwd
  end
  puts Dir.pwd
end
puts Dir.pwd
like image 68
Carl Suster Avatar answered Sep 02 '26 12:09

Carl Suster