I've this simple bash variable, in which i'm just checking if a port is open on a host, then if it's open the variable is the first host, else it's the second one.
Case 1:
set -x;
var=$(if $(netcat -zvw2 1.1.1.1 53 2>&1 | grep -o open);
then var="1.1.1.1"; else var="8.8.8.8";
fi;
echo $var);
set +x;
echo $var
+++ netcat -zvw2 1.1.1.1 53
+++ grep -o open
++ open
++ var=1.1.1.1
++ echo 1.1.1.1
+ var=1.1.1.1
+ set +x
1.1.1.1
Case 2:
set -x;
var=$(if $(netcat -zvw2 1.1.1.1 53 2>&1 | grep -o open);
then var="1.1.1.1"; else var="2.2.2.2";
fi);
set +x;
echo $var
+++ netcat -zvw2 1.1.1.1 53
+++ grep -o open
++ open
++ var=1.1.1.1
+ var=
+ set +x
What I do not understand is why in case2 the variable gets reset.
I mean, in case1 I'm echoing the result just obtained and so I'm "forcing it" as the variable output, but in case2 I suppose the result should still be kept after the 'if loop', intead as the trace shows, "var" becomes empty.
Probably it's something really basic about how bash works that I'm missing.
I believe that this is not the exact same thing as "shopt -s lastpipe" that I found in my previous research on StackOverflow.
UPDATE: "open" is clearly a typo (as KamilCuk noticed), I just didn't notice because "open" exists on my system as a part of the "mail-utils" package. I didn't even know about this command until few moments ago. It just gives a empty result if launched without any parameter so it wasn't giving any error.
This edit below should fix the above twisted logic and command substition abuse:
if [ -n "$(netcat -zvw2 1.1.1.1 53 2>&1 | grep -o open)" ]; then var="1.1.1.1"; else var="8.8.8.8"; fi