Question

Try to bear with me as I am fairly new to this and don't have much coding experience.

Im trying to use a ruby script to add a location to my PATH variable. So far I just have

path = ENV['PATH'].to_s

ENV['PATH'] = path + ";" + location

print ENV['PATH']

The problem is that the file seems to be added to the PATH and prints with it, but when I go check my path variable the new location is not there.

Also, when I run a separate script of which is one line:

print ENV['PATH']

the new location is not there either.

My question is is there a way to make the new PATH "save" instead of reverting to the old PATH when the script is finished?

Was it helpful?

Solution

If i am not mistaken you cannot really edit the environment variables.

When loading your script ruby loads all the currently known environment variables and adds the values to ENV.

When editing it, it will only be changed temporarily for the current execution.

If you want to change it and want it to persist you will have to e.g. use system

system("export PATH=$PATH:YOUR_PATH")

Same as you would do it in the CLI

OTHER TIPS

The best you can do is generate a shell command to be evaluated outside the Ruby script and inside the shell you are running.

Something like this should work:

puts "export PATH=#{ENV['PATH']};#{location}"

Then, in the shell you do

eval $(ruby_script)

However, since you seem to want to run this in Windows you probably want to use command substitution, in which case you output the location directly:

puts location

And in the Windows shell:

set PATH=%PATH%;(ruby_script)

colon ":" is the field separator for PATH not semicolon ";" in Unix. Your example worked just fine for me today when I changed the semicolon to a colon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top