문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top