0

I'm on Ubuntu 14.04 with Ruby 1.9.3. I'm trying to present an editable input to the user. The only solution I happened to find was using the read command from the bash-shell: read -e -i "Default Value" -p "Prompt> " ; echo $REPLY Executed from the command line it works well, the edited input is in the REPLY variable. But if I define

def edits
  `read -e -i "Default Value" -p "Prompt> ; echo $REPLY" ` 
end

and run it in ruby I get an error:

sh: 1: read: Illegal option -e

My questions are now:

  1. What went wrong in my solution?
  2. Is there a better solution in ruby?
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Jogan Thums
  • 227
  • 1
  • 2
  • 9

1 Answers1

0

The -e flag for read is a bash extension. You're using the sh shell (or something emulating sh), which has the read command but doesn't have that flag.

The Readline module provides terminal input, with editing, from within Ruby:

require "readline"
while buf = Readline.readline("> ", true)
  p buf
end

It also has history and completion features.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • My emphasis is not on the prompt, which readline gives, but on the "Default Value" string, that a user can edit. Can readline display such a string to edit? – Jogan Thums Sep 10 '15 at 08:04
  • If I define def shell `echo $SHELL` end, I get /bin/bash, so ruby is always calling a bash-shell, in which read -e should run??? – Jogan Thums Sep 10 '15 at 08:09
  • You can insert your default text in Readline's pre input hook (see [here](http://stackoverflow.com/a/29743124/182402)). – Wander Nauta Sep 10 '15 at 09:48
  • The `$SHELL` variable contains your default shell, not the shell that's currently running (see [here](http://unix.stackexchange.com/a/45459/94707)). – Wander Nauta Sep 10 '15 at 09:55
  • You're on Ubuntu, which means `/bin/sh` points to `dash`, not `bash`, which is what Ruby will use. – Wander Nauta Sep 10 '15 at 10:10
  • Thank you Wander, unfortunately I'm running ruby 1.9.3 which doesn't yet know Readline's pre input hook... – Jogan Thums Sep 10 '15 at 12:25
  • Right, hmm. You could call bash from dash (`bash -c`) but it would add a hard dependency on bash. You could also try something like Highline. – Wander Nauta Sep 10 '15 at 12:53
  • Wander, I followed your suggestion and did `bash -c "read -e -i 'Default Value' EDITED"; echo $EDITED` Then the input and editing works fine, but the return is always "\n" instead of the string in $EDITED. – Jogan Thums Sep 10 '15 at 13:49
  • You might need to escape the dollar sign. – Wander Nauta Sep 10 '15 at 13:50
  • Wonderful, changing $EDITED in \\$EDITED finally did it! – Jogan Thums Sep 10 '15 at 14:40