shell 脚本的每个项目和全局后备配置

问题描述 投票:0回答:1

我有一些用于个人开发的 shell 函数。我想在每个项目的基础上创建配置文件,以便函数读取配置文件并使用配置文件中的值(如果存在)。

这是一个非常基本的例子:

路径/to/project/functions.sh(有效)

#!/usr/bin/env bash

PROJECT_KEY="abc"

function project_name() {
  if [ -f .config ]; then
    . .config
  fi

  echo $PROJECT_KEY # => "def"
}

路径/到/项目/.config

PROJECT_KEY="def"

上面的方法有效,但是我有几十个这样的实用程序/帮助器函数,并且我想通过另一个函数加载配置(如果存在)。

path/to/project/functions.sh(不起作用)

#!/usr/bin/env bash
function load_config() {
  if [ -f .config ]; then
    . .config
  elif [ -f ~/.config ]; then
    . ~/.config
  fi
}

function project_name() {
  load_config

  echo $PROJECT_KEY # => "abc"
}

我相信

load_config()
函数将配置文件获取到
load_config()
函数中,然后当该函数返回/退出时,源变量就消失了,因为它们的范围仅限于单个函数调用,即
load_config() 
功能。

我知道我当前的方法不起作用,但我不知道如何避免到处执行

source .config
。我想把它放在一个被调用的函数中。

如何在函数中干净地读取配置文件而不需要大量重复代码?

更新时间 2024-05-14 17:00 美国东部时间

我有一个“工作”版本,这是更新的代码。但这看起来仍然很笨拙。

function config_file() {
  if [[ -f .config ]]; then
    echo .config
  elif [[ -f $HOME/.config ]]; then
    echo $HOME/.config
  fi
}

function project_name() {
  [[ -f $(config_file) ]] && source $(config_file)

  echo $PROJECT_KEY # => outputs the value from the config file...
}
bash function config
1个回答
0
投票

我没有找到解决您问题的好方法,但我写了一些更明智的东西,仅在需要时才获取配置文件:

~/.config

PROJECT_KEY=foo

~/proj/.config

PROJECT_KEY=bar

#!/bin/bash

# global variable for storing the path of the latest sourced config
_CURRENT_CONFIG_FILE=

load_config() {
    local config_file
    if [[ -f .config ]]
    then
        config_file=$PWD/.config
    elif [[ -f ~/.config ]]
    then
        config_file=~/.config
    else
        # no config file found
        return 1
    fi
    if [[ $_CURRENT_CONFIG_FILE != $config_file ]]
    then
        . "$config_file" && _CURRENT_CONFIG_FILE=$config_file
    fi
}

my_function() {
    load_config
    echo "$PROJECT_KEY"
}

现在让我们尝试一下:

$ cd /tmp
$ my_function
foo
$ cd ~/proj
$ my_function
bar
© www.soinside.com 2019 - 2024. All rights reserved.