从 shell 脚本读取配置文件

发布于 2024-11-07 01:37:30 字数 146 浏览 3 评论 0原文

我正在寻找类似于 Python 的 ConfigParser 或 Perl 的 Config::INI 之类的 shell 脚本。我过去已经获取了文件来完成此任务,但我更喜欢阅读而不是执行我的“配置文件”。有谁知道可用于 shell(或 bash)脚本的与上述模块类似的东西吗?

I am looking for a shell script analog to something like Pythons's ConfigParser or Perl's Config::INI. I have sourced files in the past to accomplish this, but I'd prefer to read rather than execute my "config file". Does anyone know of anything comparable to the above modules available for shell (or bash) scripts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寄与心 2024-11-14 01:37:30

你不想获取它,所以你应该:

1.读取配置,2.验证行 3.评估它们

CONFIGFILE="/path/to/config"
echo "=$ADMIN= =$TODO= =$FILE=" #these variables are not defined here
eval $(sed '/:/!d;/^ *#/d;s/:/ /;' < "$CONFIGFILE" | while read -r key val
do
    #verify here
    #...
    str="$key='$val'"
    echo "$str"
done)
echo =$ADMIN= =$TODO= =$FILE= #here are defined

配置文件的示例

ADMIN: root
TODO: delete

var=badly_formtatted_line_without_colon

#comment
FILE: /path/to/file

,如果运行上面的示例应该得到(未测试):

== == ==
=root= =delete= =/path/to/file=

当然这不是最好的解决方案- 也许有人发布了更好的帖子。

You don't want source it, so you should:

1.read the config, 2.verify lines 3.eval them

CONFIGFILE="/path/to/config"
echo "=$ADMIN= =$TODO= =$FILE=" #these variables are not defined here
eval $(sed '/:/!d;/^ *#/d;s/:/ /;' < "$CONFIGFILE" | while read -r key val
do
    #verify here
    #...
    str="$key='$val'"
    echo "$str"
done)
echo =$ADMIN= =$TODO= =$FILE= #here are defined

sample of config file

ADMIN: root
TODO: delete

var=badly_formtatted_line_without_colon

#comment
FILE: /path/to/file

if you run the above sample should get (not tested):

== == ==
=root= =delete= =/path/to/file=

sure this is not the best solution - maybe someone post a nicer one.

终弃我 2024-11-14 01:37:30

您可能想看一下 cfget,它可以通过 sudo apt-get install cfget 来安装。

You might want to take a look at cfget which can be installed with sudo apt-get install cfget.

挽你眉间 2024-11-14 01:37:30
#!/bin/bash 
# Author: CJ
# Date..: 01/03/2013

## sample INI file save below to a file, replace "^I" with tab
#^I [    SECTION ONE     ]  
#TOKEN_TWO^I ="Value1 two   "
#TOKEN_ONE=Value1 One
#TOKEN_THREE=^I"Value1^I three" # a comment string
#TOKEN_FOUR^I=^I"^IValue1 four"
#
#[SECTION_TWO]  
#TOKEN_ONE=Value1 One ^I^I^I# another comment string
#TOKEN_TWO^I ="Value1 two   "
#TOKEN_THREE=^I"Value1^I three"
#TOKEN_FOUR^I=^I"^IValue1 four"
## sample INI file

export INI= # allows access to the parsed INI values in toto by children
iniParse() {
    # Make word separator Linefeed(\n)
    OIFS="${IFS}"
    IFS=$(echo)

    SECTION=_
    while read LINE; do {
        IFS="${OIFS}"

        # Skip blank lines
        TMP="$(echo "${LINE}"|sed -e "s/^[ \t]*//")"
        if [ 0 -ne ${#TMP} ]; then
            # Ignore comment lines
            if [ '#' == "${LINE:0:1}" -o '*' == "${LINE:0:1}" ]; then
                continue
            fi # if [ '#' == "${LINE:0:1}" -o '*' == "${LINE:0:1}" ]; then

            # Section label
            if [ "[" == "${LINE:0:1}" ]; then
                LINE="${LINE/[/}"
                LINE="${LINE/]/}"
                LINE="${LINE/ /_}"
                SECTION=$(echo "${LINE}")_
            else
                LINE="$(echo "${LINE}"|sed -e "s/^[ \t]*//")"
                LINE="$(echo "${LINE}"|cut -d# -f1)"

                TOKEN="$(echo "${LINE:0}"|cut -d= -f1)"
                EQOFS=${#TOKEN}
                TOKEN="$(echo "${TOKEN}"|sed -e "s/[ \t]*//g")"

                VALUE="${LINE:${EQOFS}}"
                VALUE="$(echo "${VALUE}"|sed -e "s/^[ \t=]*//")"
                VALUE="$(echo "${VALUE}"|sed -e "s/[ \t]*$//")"

                if [ "${VALUE:0:1}" == '"' ]; then
                    echo -n "${SECTION}${TOKEN}=${VALUE}"
                    echo -e "\r"
                else
                    echo -n "${SECTION}${TOKEN}="\"${VALUE}\"""
                    echo -e "\r"
                fi # if [ "${VALUE:0:1}" == '"' ]; then
            fi # if [ "[" == "${LINE:0:1}" ]; then 
        fi # if [ 0 -ne ${#TMP} ]; then

        IFS=$(echo)
    } done <<< "$1"

    IFS="${OIFS}" # restore original IFS value
} # iniParse()

# call this function with the INI filespec
iniReader() {
    if [ -z "$1" ]; then return 1; fi

    TMPINI="$(<$1)"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/\r//g")"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/[ \t]*\[[ \t]*/[/g")"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/[ \t]*\][ \t]*/]/g")"

    INI=`iniParse "${TMPINI}"`
    INI="$(echo "${INI}"|sed -e "s/\r/\n/g")"
    eval "${INI}"

    return 0
} # iniReader() {

# sample usage
if iniReader $1 ; then
    echo INI read, exit_code $? # exit_code == 0
    cat <<< "${INI}"
    cat <<< "${SECTION_ONE_TOKEN_FOUR}"
    cat <<< "${SECTION_ONE_TOKEN_THREE}"
    cat <<< "${SECTION_TWO_TOKEN_TWO}"
    cat <<< "${SECTION_TWO_TOKEN_ONE}"
else
    echo usage: $0 filename.ini
fi # if iniReader $1 ; then
#!/bin/bash 
# Author: CJ
# Date..: 01/03/2013

## sample INI file save below to a file, replace "^I" with tab
#^I [    SECTION ONE     ]  
#TOKEN_TWO^I ="Value1 two   "
#TOKEN_ONE=Value1 One
#TOKEN_THREE=^I"Value1^I three" # a comment string
#TOKEN_FOUR^I=^I"^IValue1 four"
#
#[SECTION_TWO]  
#TOKEN_ONE=Value1 One ^I^I^I# another comment string
#TOKEN_TWO^I ="Value1 two   "
#TOKEN_THREE=^I"Value1^I three"
#TOKEN_FOUR^I=^I"^IValue1 four"
## sample INI file

export INI= # allows access to the parsed INI values in toto by children
iniParse() {
    # Make word separator Linefeed(\n)
    OIFS="${IFS}"
    IFS=$(echo)

    SECTION=_
    while read LINE; do {
        IFS="${OIFS}"

        # Skip blank lines
        TMP="$(echo "${LINE}"|sed -e "s/^[ \t]*//")"
        if [ 0 -ne ${#TMP} ]; then
            # Ignore comment lines
            if [ '#' == "${LINE:0:1}" -o '*' == "${LINE:0:1}" ]; then
                continue
            fi # if [ '#' == "${LINE:0:1}" -o '*' == "${LINE:0:1}" ]; then

            # Section label
            if [ "[" == "${LINE:0:1}" ]; then
                LINE="${LINE/[/}"
                LINE="${LINE/]/}"
                LINE="${LINE/ /_}"
                SECTION=$(echo "${LINE}")_
            else
                LINE="$(echo "${LINE}"|sed -e "s/^[ \t]*//")"
                LINE="$(echo "${LINE}"|cut -d# -f1)"

                TOKEN="$(echo "${LINE:0}"|cut -d= -f1)"
                EQOFS=${#TOKEN}
                TOKEN="$(echo "${TOKEN}"|sed -e "s/[ \t]*//g")"

                VALUE="${LINE:${EQOFS}}"
                VALUE="$(echo "${VALUE}"|sed -e "s/^[ \t=]*//")"
                VALUE="$(echo "${VALUE}"|sed -e "s/[ \t]*$//")"

                if [ "${VALUE:0:1}" == '"' ]; then
                    echo -n "${SECTION}${TOKEN}=${VALUE}"
                    echo -e "\r"
                else
                    echo -n "${SECTION}${TOKEN}="\"${VALUE}\"""
                    echo -e "\r"
                fi # if [ "${VALUE:0:1}" == '"' ]; then
            fi # if [ "[" == "${LINE:0:1}" ]; then 
        fi # if [ 0 -ne ${#TMP} ]; then

        IFS=$(echo)
    } done <<< "$1"

    IFS="${OIFS}" # restore original IFS value
} # iniParse()

# call this function with the INI filespec
iniReader() {
    if [ -z "$1" ]; then return 1; fi

    TMPINI="$(<$1)"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/\r//g")"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/[ \t]*\[[ \t]*/[/g")"
    TMPINI="$(echo "${TMPINI}"|sed -e "s/[ \t]*\][ \t]*/]/g")"

    INI=`iniParse "${TMPINI}"`
    INI="$(echo "${INI}"|sed -e "s/\r/\n/g")"
    eval "${INI}"

    return 0
} # iniReader() {

# sample usage
if iniReader $1 ; then
    echo INI read, exit_code $? # exit_code == 0
    cat <<< "${INI}"
    cat <<< "${SECTION_ONE_TOKEN_FOUR}"
    cat <<< "${SECTION_ONE_TOKEN_THREE}"
    cat <<< "${SECTION_TWO_TOKEN_TWO}"
    cat <<< "${SECTION_TWO_TOKEN_ONE}"
else
    echo usage: $0 filename.ini
fi # if iniReader $1 ; then
漆黑的白昼 2024-11-14 01:37:30

基于 grep 的替代方案似乎更具可读性:

CONFIG_FILE='/your/config/file.ini'
eval $(grep '^\[\|^#' CONFIG_FILE -v | while read line
  do echo $line
done)

其中:

  • -v grep 选项表示排除匹配行
  • ^\[\|^# 选择所有行以 [# 开头(配置解析器部分和注释)

仅当您的配置文件 = 周围没有空格时它才会起作用(如果您想使用 Python 使用 space_around_delimiters=False 生成配置,请参阅 https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write

支持的配置示例:

FIRST_VAR="a"

[lines started with [ will be ignored]
secondvar="b"

# some comment
anotherVar="c"

grep based alternative seems to be more readable:

CONFIG_FILE='/your/config/file.ini'
eval $(grep '^\[\|^#' CONFIG_FILE -v | while read line
  do echo $line
done)

Where:

  • -v grep option means exclude matching lines
  • ^\[\|^# selects all lines which starts with [ or # (configparser sections and comments)

It will work ONLY if your config file doesn't have spaces around = (if you would like to generate config with Python use space_around_delimiters=False see https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write)

Supported config example:

FIRST_VAR="a"

[lines started with [ will be ignored]
secondvar="b"

# some comment
anotherVar="c"
思慕 2024-11-14 01:37:30

您可以使用 bash 本身来解释 ini 值,方法是:

$ source <(grep = file.ini)

示例文件:

[section-a]
  var1=value1
  var2=value2

查看更多示例:如何在 a 中获取 INI 值shell 脚本?

或者您可以使用 bash ini-parser,可以在 老派 DevOps 博客网站

You can use bash it-self to interpret ini values, by:

$ source <(grep = file.ini)

Sample file:

[section-a]
  var1=value1
  var2=value2

See more examples: How do I grab an INI value within a shell script?

Or you can use bash ini-parser which can be found at The Old School DevOps blog site.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文