【问题标题】:Tcsh and Bash InitializationTcsh 和 Bash 初始化
【发布时间】:2010-09-02 15:17:46
【问题描述】:

我希望能够获取一个文件来设置一些环境变量,但这样做是为了使其独立于所使用的 shell。

例如

%: source START.env

# START.env
if [ $SHELL == "bash" ]; then
  source START.env.bash  # sets environment variables
else
  source START.env.tcsh  # sets environment variables
fi

但是,此代码仅适用于 bash。如何使它与 bash 和 tcsh 兼容?

我必须获取文件,因为我希望环境变量在之后保持不变。

【问题讨论】:

    标签: bash shell environment-variables tcsh


    【解决方案1】:

    为 tcsh 创建变量文件:

    setenv FOO 42
    setenv BAR baz
    setenv BAZ "foo bar"
    

    在您的 tcsh 脚本中使用:

    source filename
    

    在您的 Bash 脚本中使用:

    while read -r cmd var val
    do
        if [[ $cmd == "setenv" ]]
        then
            declare -x "$var=$val"
        fi
    done < filename
    

    创建一个可以在 tcsh 和 Bash 上运行的脚本会有些困难。

    【讨论】:

      【解决方案2】:

      你可以按照丹尼斯所说的去做。或者我觉得这句话更有说服力

      (在 bash 中)

      sed -i 's/setenv \([a-zA-Z0-9_]*\) /declare -x \1=/g' filename
      source filename
      

      (在 tcsh 脚本中)

      sed -i 's/declare -x \([a-zA-Z0-9_]*\)=/setenv \1 /g' filename
      source filename
      

      (请注意,这实际上会在每次运行时将源文件更改为适当的语法。)

      【讨论】:

        【解决方案3】:

        所以我最终采用了完整的 DSL 方法来解决这个问题(请参阅 clamshell)。

        【讨论】:

          猜你喜欢
          • 2016-11-24
          • 2014-08-13
          • 1970-01-01
          • 2011-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-08
          相关资源
          最近更新 更多