tags:

views:

37

answers:

3

I can run Bash shell commands from with a Ruby program or irb using backticks (and %x(), system, etc). But that does not work with history for some reason.

For example:

jones$ irb --simple-prompt
>> `whoami`
=> "jones\n"
>> `history`
(irb):2: command not found: history
=> ""

From within a Ruby program it produces this error:

/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31: command not found: history

In bash itself, those commands work fine

It's not that the Ruby call is invoking a new shell - it simply does not find that command...

Anyone know why? I'm stumped...

A: 
{~} ∴ which history
history: shell built-in command
Tass
A: 

It's a built-in. In general, you can run built-ins by manually calling the shell:

`bash -c 'history'`

However, in this case, that will probably not be useful.

Matthew Flaschen
+5  A: 

Most unix commands are implemented as executable files, and the backtick operator gives you the ability to execute these commands from within your script. However, some commands that are interpreted by bash are not executable files; they are features built-in to the bash command itself. history is one such command. The only way to execute this command is to first execute bash, then ask it to run that command.

You can use the command type to tell you the type of a particular command in order to know if you can exec it from a ruby (or python, perl, Tcl, etc script). For example:

$ type history
history is a shell builtin
$ type cat
cat is /bin/cat

You'll also find that you can't exec aliases defined in your .bashrc file either, since those aren't executable files either.

It helps to remember that exec'ing a command doesn't mean "run this shell command" but rather "run this executable file". If it's not an executable file, you can't exec it.

Bryan Oakley