Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9127

How to use Bash aliases from a shell in a Ruby script on OS X?

How can I execute aliases from my Bash shell in a Ruby script?

Here's the code:

aliases = [ 'ul', 'ur', 'dl', 'dr', 'll', 'rr', 'up', 'down', 'big', 'cen' ]

while true
    a = aliases.sample
    `#{a}`
    puts `figlet -f doh "#{a}"`
end

I would like to:

However:

Upvotes: 0

Views: 1333

Answers (4)

user1934428
user1934428

Reputation: 22217

  1. The word alias is a keyword in Ruby, so you can't use it as an identifier.

  2. When you do a source xxxx from Bash, it interprets the file "xxxx" as a Bash program. Your file is a Ruby program, so it can't be sourced.

Upvotes: 0

Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9127

It turns out that the solution is to run the shell commands inside the Ruby script as an interactive shell (so that .bashrc is sourced and aliases are available to shell's environment):

aliases = [ 'ul', 'ur', 'dl', 'dr', 'll', 'rr', 'up', 'down', 'big', 'cen' ]

while true
    a = aliases.sample
    `bash -ic '#{a}'`
    puts `figlet -f doh "#{a}"` 
end

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160551

A quick check of the Bash man page showed:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

A quick search for "shell shopt expand_aliases" showed a bunch of hits.

See "Difference between .bashrc and .bash_profile", "Why aliases in a non-interactive Bash shell do not work", "Why doesn't my Bash script recognize aliases?" and "Non-interactive shell expand alias".

Upvotes: 3

Aetherus
Aetherus

Reputation: 8888

alias is a keyword and should never be used as a variable name or a method name.

Upvotes: 0

Related Questions