如何在带有ruby的反引号运算符中使用bash_profile中定义的别名?

问题描述 投票:0回答:1

经过长时间的谷歌搜索和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

感谢帮助。

ruby bash
1个回答
0
投票
res = `bash -c "source /Users/thatsme/.bash_profile; shopt -s expand_aliases
say_hello"`
  • 需要shopt,因为当shell不是交互式时,别名不会扩展
  • <newline>是必要的,因为别名在解析时扩展。 bash解析该行并尝试扩展别名。只有在那之后才执行命令(包括source)。因此,您需要将它放在一个新的行上
© www.soinside.com 2019 - 2024. All rights reserved.