How do I make ruby's `system` call aware of my

2019-07-21 09:09发布

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.

2条回答
趁早两清
2楼-- · 2019-07-21 09:34

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
)
查看更多
等我变得足够好
3楼-- · 2019-07-21 09:49

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.

查看更多
登录 后发表回答