0

I am having some problems comparing a variable from a script to the IP address of the system. I have a source file for an app which is not bash fiendly but it has a value set like so

DKUS_MASTER=127.0.0.1

I am fetching that variable in my bash file by doing

DKUSMASTER=`grep "DKUS_MASTER" /root/somestuff.conf |  sed 's/DKUS_MASTER=//'`

Here is what i am then doing in my script as i am trying to see if eth0 ip is set to the DKUS_MASTER parameter i am fetching

DKUSMASTER=`grep "DKUS_MASTER" /root/somestuff.conf|  sed 's/DKUS_MASTER=//'`
ETH0=$(ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1)
if [ "$ETH0" = "$DKUSMASTER" ]; then
  DKUS_STATUS="Master"
else
  DKUS_STATUS="Slave"
fi

doing some testing, i can see the variables look correct

echo $DKUSMASTER
echo $ETH0

however, the end status is else false and never true as seen here. In my case the variable $DKUSMASTER does indeed equal to $ETH0, so the status should come back as master.

echo $DKUS_STATUS
  • Please properly format your question with code blocks. See [here](https://meta.stackexchange.com/questions/216464/how-to-insert-code-properly-on-stack-overflow) for ways to do that. – jeremysprofile Sep 01 '20 at 16:01
  • 1
    Running with trace-level logging -- `bash -x yourscript` -- is another good place to start, to be sure that values that _look_ identical _really are_ identical. You can't trust `echo` to tell you the truth, _especially_ when you aren't quoting the values you pass it correctly (see [I just assigned a variable, but `echo $variable` prints something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else)). – Charles Duffy Sep 01 '20 at 16:05
  • 2
    There's probably a difference in whitespace, which you can't see with simple echo. – Barmar Sep 01 '20 at 16:06
  • Also, `... | grep | awk | cut` is silly; just make your `awk` command do the work of the `grep` and the `cut`. For example: `eth0=$(ip -o addr show eth0 | awk -F'[[:space:]/]+' '$3 == "inet" { print $4; exit; }')` – Charles Duffy Sep 01 '20 at 16:06
  • (as another aside not directly related to your real problem, all-caps names are used for variables meaningful to the shell and operating-system-defined tools; per POSIX recommendations, you should use lower-case names for your own, application-defined variables to not overwrite any such system-meaningful names by accident). – Charles Duffy Sep 01 '20 at 16:11
  • @heptadecagram, `[ var1 == var2 ]` is wrong. POSIX **only** defines a single `=` as a string-comparison operator; everything else, including `==`, is nonstandard. See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Sep 01 '20 at 16:12

0 Answers0