2011-05-12 10 views
12

Estoy buscando un script de shell análogo a algo como ConfigParser de Pythons o Config :: INI de Perl. He obtenido archivos en el pasado para lograr esto, pero preferiría leer en lugar de ejecutar mi "archivo de configuración". ¿Alguien sabe de algo comparable a los módulos anteriores disponibles para scripts shell (o bash)?Lectura de un archivo de configuración de un script de shell

Gracias, Jerry

+1

posible duplicado de [¿Cómo puedo obtener un valor INI dentro de un script de shell?] (Http://stackoverflow.com/questions/6318809/how-do-i-grab-an-ini-value-within-a -shell-script) – kenorb

Respuesta

12

Usted no quiere que la fuente, por lo que debe:

1.read la configuración, las líneas 2.Compruebe ellos 3.eval

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 

muestra del archivo de configuración

ADMIN: root 
TODO: delete 

var=badly_formtatted_line_without_colon 

#comment 
FILE: /path/to/file 

si ejecuta la muestra anterior debería obtener (no probado):

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

Seguro que esta no es la mejor solución, tal vez alguien publique una mejor.

+0

Supongo que estaba pensando en algo preempacado como ConfigParser, pero esto ciertamente funciona. ¡Gracias! – zenzic

+0

Para manejar líneas en blanco en el archivo de configuración: 'eval $ (sed '/^* #/d; s /://;' <" $ CONFIGFILE "| while read key val hacer si [-n" $ {key } "]; then str =" $ key = '$ val' " echo" $ str " fi done)' – slonik

+0

@slonik Buen punto para manejar líneas en blanco. En el script, 'sed' filtra las líneas no deseadas, por lo que hay suficiente para agregar otro comando, como:'/^ * $/d' (por ejemplo, eliminar líneas que contienen solo cualquier cantidad de espacios, por ejemplo, cero o más). Gracias, señalándome el problema. Editado mi respuesta. – jm666

3
#!/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 
3

Es posible que desee echar un vistazo a cfget que se puede instalar con sudo apt-get install cfget.

+0

Esa es una herramienta realmente útil si tiene los derechos para instalarla en su sistema. –

Cuestiones relacionadas