Skip to content

Instantly share code, notes, and snippets.

@botanicus
Created June 15, 2014 18:12
Show Gist options
  • Select an option

  • Save botanicus/75b070b3247f265fe61b to your computer and use it in GitHub Desktop.

Select an option

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.
#!/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
@botanicus
Copy link
Copy Markdown
Author

cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

sudo ./env-edit.rb PATH append /opt/node-0.10.28/bin

cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/node-0.10.28/bin"

@ivystopia
Copy link
Copy Markdown

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