设置环境变量的Shell脚本

百科知识2025-04-261

0  

If you really want this to happen, it can be done, but it's tricky. One way to do it is to use awk to output the correct syntax and evaluate the text coming back from awk. To share a single environment variable value file between major sh and csh flavors, the following command in a file will import a variable value file to the environment: (yes, yes, it's one huge line, due to the inflexible way that some shells treat the backticks. If you didn't mind having a .awk file too, you could use awk -f...)

如果你真的想这样做,这是可以做到的,但这很棘手。一种方法是使用awk输出正确的语法并评估从awk返回的文本。要在主要的sh和csh风格之间共享一个环境变量值文件,文件中的以下命令将向环境导入一个变量值文件:(是的,是的,这是一行很大的一行,因为一些shell处理回签的方式不灵活。如果你不介意有一个。awk文件,你可以使用awk -f…)

eval awk '{ var = $1; $1=""; val=substr($0,2); if ( ENVIRON["SHELL"] ~ /csh$/) { print "setenv", var, " \"" val "\";" } else { print var "=\"" val "\"" ; print "export", var }}' $HOME/env_value_file

The variable value file is in this format:

可变值文件的格式如下:

FOO value for foo
BAR foo bar
BAZ $BAR plus values $FOO

Design notes for educational purposes:

教育用途设计说明:

  1. In awk, there's no easy way of accessing fields 2-NF, so if there could be spaces in our variable values we need to modify $1 to get $0 to be close to get the value we want.
  2. 在awk中,没有简单的方法访问字段2-NF,所以如果变量值中有空格,我们需要修改$1以使$0接近我们想要的值。
  3. To get this to work, since a SHELL variable is always set, but not as an environment variable and not with a consistent capitalization, you have to wet a SHELL environment variable from the shell's value as below. as an environment variable before you use the script.
  4. 要使其工作,由于始终设置SHELL变量,但不作为环境变量,也不具有一致的大小写,因此必须从SHELL的值中提取SHELL环境变量,如下所示。在使用脚本之前作为环境变量。
  5. Also, if you want the new environment values to be present after the import environment script you need to source the environment script.
  6. 此外,如果您希望在导入环境脚本之后出现新的环境值,您需要为环境脚本提供源代码。
  7. If a shell doesn't do eval well, you'll have to tweak the script.
  8. 如果shell不能很好地完成eval,您将不得不调整脚本。

For bourne shell flavors (bash, sh, ksh, zsh):

伯恩壳口味(bash, sh, ksh, zsh):

export SHELL
. import_environment

For csh flavors: (shell variable tends to be lower case in csh shells)

对于csh口味:(在csh壳中,壳变量往往是小写的)

setenv SHELL "$shell"
source import_environment