0

In Ruby, on osx, how can I change the prompt from within a ruby script?

For example,

I'd like a ruby script to run some code and depending on the result, do PS1='\w$ '. or PS1='\t$ '

i.e.

~ $PS1='\w $'
~ $

~ $PS1='\t $'
20:52:23 $

So as a start I've just tried a script to change the prompt

~/$ cat scripttochangeprompt.rb 
`export PS1='\t$ '`
~/$ 

but it doesn't change the prompt.

~/$ ruby ./scripttochangeprompt.rb 
~/$ 

I can guess that it's creating a new console session to run the command then closing that new console session. But how can I get it to run it in this console session?

barlop
  • 12,887
  • 8
  • 80
  • 109

2 Answers2

2

Ruby will always run in a subprocess. A subprocess cannot change the environment of a parent process. However, it can output things in a format that is convenient for parent process to evaluate. This is how e.g. ssh-agent sets its environment variables.

#!/usr/bin/env ruby
puts "export PS1='\t$ '"

Then execute it like this:

eval `changeprompt.rb`
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

There are several ways to work with shell command execution and you use the one that executes the command in the current ruby process and returns its result to your script. With such an approach this proccess cannot mutate a shell it was called from, so it is unfitting. Other ways of interaction with the shell also use child processes or current ruby process one way or another. Unfortunately, in most OS you cannot set an environment variable of parent process(namely, shell) from child process(namely, your ruby script). Here are stackoverflow issue and an article on that matter. There are some hacks in the issue provided that can satisfy you in practice, but they seem obscure and awkward to me.