4

I want to be able to run a command to get a property from a property file. So if my properties file is property.props and has

username=dsollen
password=letMeIn
linux-skills=newb

I would like to have a quick way to pull out the property to pipe into other commands. so

 ./myProgram -v -p `getProp property.props password`

or something like that; not sure I used the ` right, but that's a different newb linux question for later :)

I know I can do this with a combination of grep and cut/awk/sed/whatever, but I'm wondering if there is an already existing tool that 'knows' how to read common property file formats and does something like this? If not I could write something to add into my scripts folder, just don't want to reinvent the wheel if a better wheel already exists.

dsollen
  • 6,046
  • 6
  • 43
  • 84

3 Answers3

7

You can use gvar to do the work. I'm the author by the way.

From the source code, this is the interesting part for you:

get_variable() {
  < "$FILE" grep -w "$1" | cut -d'=' -f2
}
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
  • You may want to check your code with shellcheck.net. – chepner Apr 29 '16 at 15:52
  • my 5 second scan of the home page suggests this is for global variables only. can it be used to simply return a variable without making it global? – dsollen Apr 29 '16 at 16:19
  • @dsollen The function he posted doesn't make it a variable, it just returns the value. You can do whatever you want with the function. – Barmar Apr 29 '16 at 16:40
2

I assume your properties keys are unique, if so then the following might be a way:

grep -w "$1" <property.props

or to get the value

(grep -w "$1" | cut -d= -f2) <property.props

Where $1 is the key.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
0

Look, just define in your .bashrc a function:

getProp() {
  awk -F "=" "/^$2=/ {print "'$2'"; exit; }" $1
}

And use it in your shell:

$ getProp property.pros password
letMeIn

$ getProp property.pros linux-skills
newb
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – CodeMouse92 Apr 29 '16 at 19:09