如何在ruby的反引号操作中使用bash配置文件中定义的别名?

时间:2017-12-31 13:55:57

标签: ruby bash

经过长时间的谷歌搜索和SOing ......

我的.bash_profile文件中定义了一些别名。例如:

alias say_hello="echo 'Hello!'"

我想在ruby的反击操作中使用它们,寻找我的bash配置文件。但我失败了。

我试过了:

# (ruby code)
res = `. /Users/thatsme/.bash_profile;say_hello`
# => sh: say_hello: command not found

甚至:

res = `. /Users/thatsme/.bash_profile;shopt -s expand_aliases;say_hello`
# => sh: say_hello: command not found

(注意:我不想在反引号操作中对别名进行硬编码)。

注意

bash个人资料来源很好。如果我将echo "I'm sourced"放入其中,我的反引号操作会回显文本。

res = `. /Users/thatsme/.bash_profile;say_hello`
# => 
    sh: say_hello: command not found
    I'm sourced

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

res = `bash -c "source /Users/thatsme/.bash_profile; shopt -s expand_aliases
say_hello"`
  • shopt是必需的,因为当shell不是交互式时不会扩展别名
  • <newline>是必要的,因为别名在解析时扩展。 bash解析该行并尝试扩展别名。只有在那之后才执行命令(包括source)。因此,您需要将其置于新的一行