简体   繁体   English

从外壳调用红宝石

[英]Calling ruby from shell

When I have an executable ruby script foo starting with a shebang 当我有一个以shebang开头的可执行的ruby脚本foo

foo

#!/usr/bin/env ruby

and call that ruby script from within a bash script bar as executable (ie, not calling ruby foo , but directly foo ), how can I get the full path of bar from within the ruby script foo ? 并从bash脚本bar调用该ruby脚本作为可执行文件(即,不调用ruby foo ,而是直接调用foo ),如何从ruby脚本foo获取bar的完整路径?


Edit 编辑

If this is not possible, then is it possible if I have a bash script baz in between so that: 如果这不可能,那么我之间可能有一个bash脚本baz ,所以有可能:

bar (bash) calls baz (bash) which calls foo (ruby) bar (bash)调用baz (bash),后者调用foo (ruby)

where bar calls baz without any explicit argument and baz figures out the path of its caller bar , and passes that as an argument when calling foo ? bar在没有任何显式参数的情况下调用bazbaz找出其调用方bar的路径,并在调用foo时将其作为参数传递?

For my purpose, it is okay whether or not foo needs to receive the path information as an argument as long as the original bash script bar does not need to pass that explicitly. 出于我的目的,只要原始bash脚bar不需要显式传递foo是否需要将路径信息作为参数都可以。

First, note that the question is not well defined. 首先,请注意,这个问题的定义不明确。 If bar is not a unique link to the executable, then there is no unique path. 如果bar不是指向可执行文件的唯一链接,则没有唯一路径。 Assuming you don't care about that issue and you just want to know how bar was accessed and if you are running on Linux that information is available in /proc/pid-of-bar/cmdline . 假设您不在乎该问题,并且只想知道bar访问方式,并且如果您在Linux上运行,则可以在/proc/pid-of-bar/cmdline找到该信息。 If foo's parent is the process running bar (it should be, unless you've daemonized or foo is not a direct descendant), the bar's pid is available to foo in the environment at PPID (although ruby almost certainly provides a better way to access the parent's pid.) So, get your parent's pid and read /proc/parent-pid/cmdline. 如果foo的父级是正在运行的进程栏(应该,除非您已将其守护,或者foo不是直接后代),否则该栏的pid可用于PPID环境中的foo(尽管ruby几乎可以肯定提供了一种更好的访问方式因此,获取您父母的pid并阅读/ proc / parent-pid / cmdline。 If bar was invoked as a shell script, the first string of cmdline will be the interpreter (terminated by a null), and the second string will be the path you care about. 如果将bar作为shell脚本调用,则cmdline的第一个字符串将是解释器(以null终止),第二个字符串将是您关心的路径。

If I understand your question $0 is all you need. 如果我理解您的问题,那么您只需要$ 0。

Edit: and of course pass this into your ruby script via the bar script. 编辑:当然可以通过条形脚本将其传递到您的ruby脚本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM