从红宝石父shell中运行命令 [英] run command in parent shell from ruby

查看:139
本文介绍了从红宝石父shell中运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变我开始通过Ruby脚本本身...

I'm trying to change the directory of the shell I start the ruby script form via the ruby script itself...

我的观点是建立一个小程序来管理您的收藏夹目录,方便它们之间改变。

My point is to build a little program to manage favorites directories and easily change among them.

下面是我所做的。

#!/usr/bin/ruby
Dir.chdir("/Users/luca/mydir")

and than tried executing it in many ways...

my_script (this doesn't change the directory)
. my_script (this is interpreted as bash)
. $(ruby my_script) (this is interpreted as bash too!)

任何想法?

推荐答案

无法完成。子进程不能修改自己的父母环境(包括父母的当前工作目录)。在(又名)欺骗,因为你是在告诉shell中运行$只能用shell脚本作品C $ c在当前进程(而不是生成一个子进程来运行它)。只是为了好玩尝试把退出在运行这样一个文件。(扰流:你会被注销)

Cannot be done. Child processes cannot modify their parents environment (including the current working directory of the parent). The . (also known as source) trick only works with shell scripts because you are telling the shell to run that code in the current process (rather than spawning a subprocess to run it). Just for fun try putting exit in a file you run this way (spoiler: you will get logged out).

如果你希望有这个工作,你需要创建一个打电话给你的Ruby脚本,并有shell函数做实际的 CD shell函数的错觉。由于函数在当前进程中运行,他们可以改变的目录。例如,给定此红宝石脚本(名为temp.rb):

If you wish to have the illusion of this working you need to create shell functions that call your Ruby script and have the shell function do the actual cd. Since the functions run in the current process, they can change the directory. For instance, given this ruby script (named temp.rb):

#!/usr/bin/ruby

print "/tmp";

您可以写这个BASH功能(在,比方说,你〜/ .profile文件

You could write this BASH function (in, say, you ~/.profile):

function gotmp {
    cd $(~/bin/temp.rb)
}

然后你可以说 gotmp 在命令行,并有目录进行更改。

And then you could say gotmp at the commandline and have the directory be changed.

这篇关于从红宝石父shell中运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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