0

I have following Bash function which return property value from Java-style property file. It property wasn't found, it should return non-zero. If found, property's value will be printed & return code must be zero.

function property_get() {
    local pfile="$1"
    local pname="$2"
    if egrep "^${pname}=" "$pfile" 2>&1 >/dev/null; then
        local line="$(egrep "^${pname}=" "$pfile")"
        printf "${line#*=}"
        return 0 # success
    else
        return 1 # property not found
    fi
}

The question is: how to avoid from calling egrep twice? First exec is for status code, 2nd is for property value. If I use $(grep parameters) notation, then grep will be launched in subshell and I can't get it's return code and won't be able to determine success or failure of property searching.

  • 1
    Why not just get the line, and then check if it was found? – matt Jun 29 '16 at 09:16
  • @matt that's looks like indirect check for me. grep already report it's success or failure by providing us return code and I would like to get advantage of that fact – Andrey Brindeyev Jun 29 '16 at 09:21
  • 1
    Something like `$?`, as per this [how to check the exit status](http://linuxcommando.blogspot.co.uk/2008/03/how-to-check-exit-status-code.html)? – matt Jun 29 '16 at 09:26
  • @matt it won't work with `$()`. I need to find a way to capture both exit code from grep & it's output from single grep invocation – Andrey Brindeyev Jun 29 '16 at 09:28
  • @AndreyBrindeyev Yes it will work. See this: http://stackoverflow.com/questions/20157938/bash-exit-code-of-variable-assignment-to-command-substitution – Julien Lopez Jun 29 '16 at 09:35
  • @julien-lopez well, it certainly failing for me: https://gist.github.com/abrindeyev/10a57177b9181dc82f30518a580f1885 – Andrey Brindeyev Jun 29 '16 at 09:52
  • 1
    Did you see the difference. It is the local command as stated in Julien's answer. – matt Jun 29 '16 at 12:38

2 Answers2

2

This should work:

...
local line
if line=$(egrep "^${pname}=" "$pfile" 2>/dev/null); then
...
mouviciel
  • 66,855
  • 13
  • 106
  • 140
0

As @matt points out, you can just get the line then check the exit status of your command:

line=$(...)
if test $? -eq 0; then
  # success
  ...
else
  # property not found
  ...
fi

Edit:

To summarize:

Community
  • 1
  • 1
Julien Lopez
  • 1,794
  • 5
  • 18
  • 24