简体   繁体   English

如何从bash脚本修改/ etc / environment

[英]How to modify /etc/environment from a bash script

Currently, I'm trying to automate a procedure we use at work. 目前,我正在尝试自动化我们在工作中使用的程序。 Whenever we install Oracle's JDK, we need to manually add it to our global PATH variable. 每当我们安装Oracle的JDK时,我们都需要手动将其添加到我们的全局PATH变量中。 Here's an excerpt from the procedure : 以下是该程序的摘录:

sudo vi /etc/environment
add this at the beginning of the PATH : "/opt/jdk1.6.0_45/bin:"

Here is the content of /etc/environment on my computer : 这是我的计算机上/etc/environment的内容:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

Here is what it will look like after its modification : 以下是修改后的样子:

PATH="/opt/jdk1.6.0_45/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

Do not forget that this file is not a script, but rather a file containing KEY=VALUES. 不要忘记这个文件不是脚本,而是包含KEY = VALUES的文件。 This file stores the system-wide locale and path settings. 此文件存储系统范围的区域设置和路径设置。

My question is how can I add a new path to the PATH variable from /etc/environment without involving any manual operation, preferably using only a bash script. 我的问题是如何在不涉及任何手动操作的情况下从/etc/environment添加PATH变量的新路径,最好只使用bash脚本。 Additionnaly, I would like to avoid seeing my JDK path added more than once if I run the resulting script twice. 另外,如果我运行两次生成的脚本,我想避免看到我的JDK路径多次添加。

You can do this using sed to first delete and then insert the jdk path: 您可以使用sed首先删除然后插入jdk路径:

#!/bin/bash
sed -e 's|/opt/jdk1.6.0_45/bin:||g' -i /etc/environment 
sed -e 's|PATH="\(.*\)"|PATH="/opt/jdk1.6.0_45/bin:\1"|g' -i /etc/environment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM