How do I make ruby's `system` call aware of my `.bash_profile` aliases?

泄露秘密 提交于 2019-12-11 02:28:02

问题


I'd like to be able to call one of my shortcuts (i.e., aliases) from within a ruby program. In other words, I want

system('cpl')

to be the equivalent of writing

cd ~/Documents/CPlusPlus

at the command line, because my .bash_profile includes the line

alias cpl="cd ~/Documents/cplusplus"

I'm on a Mac OSX, and while my .bash_profile lives in the usual place (~), I might be writing ruby in/to any old folder. I am using Ruby 2.2.0 which is located in /usr/local/bin/ruby.


回答1:


From source docs:

Read and execute commands from the filename argument in the current shell context.

From shopt -s expand_aliases docs:

If set, aliases are expanded. This option is enabled by default for interactive shells.

You use non-interactive shell, so this additional step is required:

system %(
  source ~/.bash_profile
  shopt -s expand_aliases
  cpl
)



回答2:


The following should work:

system("bash -ci 'cpl'")

The c switch tells to "execute" cpl as a command instead of searching for a file. The i turns bash into interactive mode and more importantly loads the .bashrc file.

EDIT: Make sure you define your alias in the .bashrc file. This file is loaded every a new shell initializes. The .bash_profile is only loaded upon every user login. See more here.



来源:https://stackoverflow.com/questions/28555822/how-do-i-make-rubys-system-call-aware-of-my-bash-profile-aliases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!