Created
June 15, 2014 18:12
-
-
Save botanicus/75b070b3247f265fe61b to your computer and use it in GitHub Desktop.
Modify /etc/environment with ease! Append, prepend to your PATH, define and undefine variables! Last version is always in /etc/environment.bckp.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/opt/rubies/ruby-2.1.2/bin/ruby -i.bckp | |
| # Usage: | |
| # ./env-edit.rb [var] delete [optional file] | |
| # ./env-edit.rb [var] [append|prepend|replace|remove] [value] [optional file] | |
| # ./env-edit.rb PATH append /opt/rubies/rbx-2.2.6/bin/rbx | |
| OPERATIONS = ['add', 'delete', 'append', 'prepend', 'replace', 'remove'] | |
| variable, operation = ARGV.shift(2) | |
| unless OPERATIONS.include?(operation) | |
| abort "Operation #{operation} is not permitted. Options are: #{OPERATIONS.inspect}" | |
| end | |
| if (OPERATIONS - ['delete']).include?(operation) | |
| value = ARGV.shift | |
| end | |
| # ARGF assumes all arguments have been deleted from ARGV. | |
| ARGV.push('/etc/environment') if ARGV.empty? | |
| def modify(serialised_array, value, method) | |
| dirs = serialised_array.split(':') | |
| dirs.send(method, value) | |
| dirs.uniq.join(':') | |
| end | |
| ARGF.each_line do |line| | |
| if match = line.match(/#{variable}="(.+)"/) | |
| new_value = case operation | |
| when 'append' then modify(match[1], value, :push) | |
| when 'prepend' then modify(match[1], value, :unshift) | |
| when 'remove' then modify(match[1], value, :delete) | |
| when 'replace' then value | |
| when 'delete' # return nil | |
| end | |
| puts line.sub(match[1], new_value) unless line.nil? || line.empty? | |
| else | |
| puts line | |
| end | |
| end | |
| # TODO: This should check where it has already been defined. | |
| if operation == 'add' | |
| puts "#{variable}=#{value}" | |
| end |
Author
botanicus
commented
Jun 15, 2014
Hi, can you please clarify the distribution license?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment