2

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.

pgblu
  • 662
  • 1
  • 7
  • 29

2 Answers2

7

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.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Works great. Btw can you please explain why ``source ~/.bashrc`` returns `sh: 1: source: not found`. I referred here: http://stackoverflow.com/a/5313701/3035830 – shivam Feb 17 '15 at 06:32
  • 1
    @shivam because there is no `source` command in `sh`, equivalent of `source` in `sh` is `.` – Rustam Gasanov Feb 17 '15 at 06:34
  • Note that this may be a bit risky if the user has something in their `.bashrc` that triggers for interactive shells, when this is not in fact an interactive shell. – Arkku Feb 17 '15 at 07:10
0

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
)
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • I think this way is less risky than invoking bash as an interactive shell when it's not an interactive shell, and thus the better solution, except that the system shell is not guaranteed to be `bash` (on OS X it very likely is, though, unless the user has changed their environment)… – Arkku Feb 17 '15 at 07:08