Running shell commands from a specific directory
Ruby seems to use /bin/sh
as the shell interpreter, which on a *nix machine doesn't understand /bin/bash
commands such as pushd
. This is what irb
tells me:
1.9.3-p327 :011 > `pushd /tmp; echo foo`
sh: 1: pushd: not found
=> "foon"
On OSX, /bin/sh
is an alias for bash, so the above snippet runs fine there. Is there a way to force Ruby on a *nix machine to use /bin/bash
for interpreting shell commands?
Using Bash commands like pushd
in Ruby is pointless, because those commands affect Bash's internal state of the Bash interpreter, and when you Run a shell command from Ruby using backticks or system
, it creates a new subprocess, runs the command, and then closes that subprocess.
That means that even if you somehow manage to run pushd
as a Bash command from Ruby, what will happen is that the the Bash subprocess will start, push the directory to the directory stack, and then exit. The changes you've made to the directory stack will be erased with all the other subprocess' data - and the next time you use a shell command you won't be at that directory.
You are scripting in Ruby, not in Bash - internal Bash commands have no meaning here, so you need to use the Ruby equivalents. For example, instead of writing:
system 'pushd /tmp'
system 'touch file_in_tmp'
system 'popd'
Which wouldn't work, what you want to do is:
Dir.chdir '/tmp' do
system 'touch file_in_tmp'
end
/bin/sh is hardcoded in the ruby source. So there is no way to change the default shell. You could use one of the other suggested approaches.
Do
Dir.chdir("/bin")
and then do your commands:
`pushd /tmp; echo foo`
链接地址: http://www.djcxy.com/p/996.html
下一篇: 从特定目录运行shell命令