在 ruby​​ 脚本中执行 cd 命令 [英] exec the cd command in a ruby script

查看:74
本文介绍了在 ruby​​ 脚本中执行 cd 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 ruby​​ 脚本中更改当前 shell 的密码.所以:

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')

不幸的是,cd 是一个内置命令.所以:

Unfortunately, cd is a builtin command. So:

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

有什么解决方法吗?

无法让它在 ruby​​ 本身中工作,所以我换了档.我修改了脚本以输出目标目录路径,然后在 .bashrc 中定义了一个函数,该函数将通过脚本传递参数,然后 cd 到正确的目录.不像我希望的那样独立,但它完成了工作.

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.

谢谢各位的回复.

推荐答案

正如其他答案已经指出的那样,您可以更改 ruby​​ 脚本中的密码,但它只会影响子进程(您的 ruby​​ 脚本).不能从子进程更改父进程的密码.

As other answers already pointed out, you can change the pwd inside your ruby script, but it only affects the child process (your ruby script). A parent process' pwd cannot be changed from a child process.

一种解决方法可能是,让脚本输出要执行的 shell 命令并在反引号中调用它(即 shell 执行脚本并将其输出作为要执行的命令)

One workaround could be, to have the script output the shell command(s) to execute and call it in backticks (i.e. the shell executes the script and takes its output as commands to execute)

myscript.rb:

myscript.rb:

# … fancy code to build somepath …
puts "cd #{somepath}"

调用它:

`ruby myscript.rb`

使用别名使其成为一个简单的命令:

make it a simple command by using an alias:

alias myscript='`ruby /path/to/myscript.rb`'

不幸的是,这样您就无法将脚本输出文本给用户,因为脚本输出的任何文本都是由 shell 执行的(尽管也有更多解决方法).

Unfortunately, this way you can't have your script output text to the user since any text the script outputs is executed by the shell (though there are more workarounds to this as well).

这篇关于在 ruby​​ 脚本中执行 cd 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆