This question already has an answer here:
I am working on a shell script that when first opened asks the user for some info. This info needs to be stored on a config file for future use so that the user doesn't have to answer the same questions every time the program opens. Of course, I am planning on writing an if statement to check whether the info is in the config file every time the script is used, but I don't know how to create a config file. I would like to know how I can do this from the shell script itself, so that if a person downloads my script and uses it the config file is created for them. I would also like to know how I can add the info into the config file from the script. Thanks for your help.
Again one OP that thinks that SO is its personal development center. You didn't even take the work to look at the other questions similar to his one, like: this or this and others.
Because you can run into serious troubles, I will recommend you a solution:
and you will find than never
source
any config variables, because it is dangerous. For example what happens when yousource
the next config file?So, you should
;
or back-tick or&
and like. Best if it will contain only [A-Za-z0-9_/] and not others. This called as sanitizing config values.The best you can do, using more powerful tool for config-file parsing, e.g. perl, awk or so.
And next time, use google or SO's search for getting answers before asking here
Ps: and sorry for the message, maybe i'm waked up in a bad mood, but starting get angry with OP's who didn't even try find a solution ourselves...
A solution I often see is to write out a config file like this:
Then, that config file is a proper shell scrip itself, and can be sourced by the shell script at startup, like so:
Sourcing it (rather than executing it as a command) ensures that all variables it defines will be visible in the script that sourced it.
Then, of course, you'd want to make user-directed customization after sourcing it, but before writing out the new version.
Caveat Emptor
Using this method is okay for something quick-n-dirty, or something only you will touch. However, sourcing a script runs all of the code in it, in the current session. That means it can
rm -rf /
, and it could also redefine functions or variables which you've defined in your main script, overriding them.You may use some code like this:
var1
andvar2
will be separated by a newline and stored in the~/.myscriptrc
config file. So, givenvar1=Foo
andvar2=Bar
, the~/.myscriptrc
file will be: