简体   繁体   中英

Reading variables from config file in Shell

I have question about Linux shell scripts. My question is realy abstract, so may not make sense. The idea is having 1 script and 2 config files.

Script can be like (drinkOutput.sh):

#!/bin/bash

echo -e " $1 \n"
echo -e " $2 \n"

First Config file contain (beer.conf):

drink1="heineken"
drink2="argus"

Second Config file contain (vine.conf):

drink1="chardonnay"
drink2="hibernal"

The key thing is calling the script. It has to be in next format (or with parameter)

./drinkOutput.sh beer.conf 

In this case I need to have in $1 heineken and in $2 argus (inside of drinkOutput script). For

./drinkOutput.sh vine.conf 

I need to get back into drinkOutput.sh chardonnay and hibernal.

Does anybody know? Thanks for any tips

You can source the config files if they are in the right format (and it seems it is in your example).

drinkOutput()
{
    echo "$1"
    echo "$2"
}

conf="$1"
source "$conf"
drinkOutput "$drink1" "$drink2"

If is possible if your script calls itself with the proper arguments after having parsed them from the conf file:

if [ $# == 2 ] ; then
   # The arguments are correctly set in the sub-shell.
   # 2 arguments: do something with them
   echo magic happens: $1 $2

elif [ $# == 1 ] ; then
   # 1 argument: conf file: parse conf file
   arg1=`sed -n -e 's#drink1="\(.*\)"#\1#p' $1`
   arg2=`sed -n -e 's#drink2="\(.*\)"#\1#p' $1`
   $0 $arg1 $arg2
else
    # error
    echo "wrong args"
fi

test:

$ drinkOutput.sh beer.conf
magic happens: heineken argus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM