Read in values from a file
Hey Guys
I currently have a code in pure /bin/sh (and has to remain the same) which basically takes input from command prompt flags.. Code:
while getopts a:b:c:d: name Code:
./config.sh -a <name> -b <age> -c <title> -d <os> The file format is going to be Code:
name: abcd Thanks (n00b) |
Does the file have to be in that exact format? If you can set it up so that the lines are already in var=value form, then you can simply source the file directly into the script.
Otherwise you'll have to parse the file for the values. Try a while+read loop with two input variables. Do this before the getopts loop and the default values will be set first. The loop will then only overwrite the defaults for any input arguments that exist. |
Why not put the defaults inside the script itself? The syntax is:
Code:
VAR=${VAR-default} Code:
NAME=${NAME-abcd} You can also use the output of a command as default value, so that if you still need to read the values from a file, you can easily parse it with awk: Code:
NAME=${NAME-`awk '/name:/{print $2}' defaults`} |
The defaults cannot be inside the script (it actually contains passwords etc) so it is in a different .file with chmod permission and stuff.. (security standards)..
The file format is not specific.. so u mean I should make the file as Quote:
Can you show how the code should look like?? thanks :) |
Once the file is in the format you have shown you can simply 'source' the file and those defaults will be set unless overwritten:
Code:
. defaults_file |
"Sourcing" an external file means to incorporate the contents of that file into your script at that point of the command, and your script will act exactly as if the lines were written there directly.
It can be called with either the "source" keyword, or more commonly with ".", a single period. So if you have a file called "defaults.txt" which contains: Code:
NAME=David Code:
#!/bin/bash Sourcing is covered in the BashGuide here: http://mywiki.wooledge.org/BashGuide/Sourcing I recommend checking out the whole thing when you have time. |
Just a little note: in /bin/sh the source keyword is not valid. The Bourne Shell accepts only . (the dot). Historically the source keyword was introduced in the C-shell and adopted by /bin/bash later on.
Chronological colucix :jawa: |
Hey Guys
Just to expand on this issue, I have a file from which I am sourcing filename: default Code:
MAN=Value1 Code:
#!/bin/sh What am I doing wrong?? EDIT: Defined the default value before the case and then pass optargs.. if it gets nothing then it takes the default value.. |
You need to review your parameter substitution:
[quote] ${parameter=default}, ${parameter:=default} == If parameter not set, set it to default. ${parameter-default}, ${parameter:-default} == If parameter not set, use default. [/code] Tricky if not careful when being read :) |
All times are GMT -5. The time now is 11:52 PM. |