0

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:

  • select a random shell alias from the aliases array. (These aliases are aliases that I can use in my shell as defined in my .bashrc),
  • execute the selected alias,
  • print the name of the selected alias to the terminal screen using figlet.

However:

  • When I execute ./mysciprt I get:

    ul: command not found
    
Community
  • 1
  • 1
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
  • Update: I was wrong to say that you cannot invoke alias from ruby code. See my question for answer: http://stackoverflow.com/questions/33705936/how-do-you-invoke-alias-from-ruby-code-for-zsh-shell/33718936#33718936 – ytbryan Nov 15 '15 at 11:33

4 Answers4

3

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".

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
2

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
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
0

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

Aetherus
  • 8,720
  • 1
  • 22
  • 36
0
  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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1934428
  • 19,864
  • 7
  • 42
  • 87