config file for your bash script

January 22nd, 2011 mysurface Posted in Bash, source | Hits: 124835 | 5 Comments »

Sometime you may wish to create a bash script to do something based on a config file, what actually was in your mind? How to implement the config file for your bash script?

First I think of using command ‘cut’, where I can create a list of tag=value, then uses ‘cut‘ to read out the tag and value. But that is so wrong, because I could just using command ‘source’ to do it instead.

Let say I have a config.ini

PATTERN="$hello*"
FILENAME=hello.txt
OUTPUT=result.txt

And I want my bash_script to read these variables and perform grep.


#!/bin/bash
source config.ini

grep ${PATTERN} ${FILENAME} > ${OUTPUT}

The keyword ‘source’ will import the variable from config.ini into my script, made them available for my use. The source line can be also replace it into this:

. config.ini

DOT(.) is equivalent to command ‘source’.

I can also source another bash script which contains if-else logics, the same way I source my config.ini.

But bare in mind, if your target source file contains ‘exit’, it will exit your parent script.

For example, I have a parent.sh sourcing config.sh, where my config.sh contain exit.

config.sh

#!/bin/bash
HELLO=world
exit

parent.sh

#!/bin/bash
source config.sh
echo ${HELLO}

When I try to execute the ./parent.sh, my script immediately exit before it execute the ‘echo’.

I hope that this post will gives you an idea of using command ‘source’ to implement your config file for your bash script.

5 Responses to “config file for your bash script”

  1. It’s great tip! Can I translate it into spanish for my blog?

    Thank in advance.

  2. @nordri, no problem, just go ahead.

  3. I just was dealing with the same quesion of ‘sourcing’ the scripts for config.

    One thing to watch though is that your config will be treated as part of script, so your assignment
    PATTERN=”$hello*”

    will get evaluated for $hello variable (not defined), and PATTERN result in “*”.

    So in this case you may need to escape special chars:
    PATTERN=”\$hello*”

    Cheers!

  4. I just enjoy Linux although have no idea how it works……

  5. Pettersen,Pandora charm discount uk, seeking her first victory over the season,Sale pandora charms uk, led after the third round but her lead was erased under the playoff-Style rules.The trousers play a major part in your dress so keep in http://www.kukura.co.uk/ mind to assort them with your Shirt or t-Shirt.What is does,Pandora charms sale uk, according to clincal research trials,pandora jewelry pandora bracelet, is increase the cheapion of elastic fibers and new skin cells. Holiday vacations

Leave a Reply