I've found a weird problem I cannot resolve.
I need to extract some values in a variable, these values are after a string.
The name of the variable in this example is: DSLSTATE
Here an example of the value in it:
NewEnable 1
NewStatus Up
NewDataPath Fast
NewUpstreamCurrRate 21598
NewDownstreamCurrRate 170788
NewUpstreamMaxRate 25692
NewDownstreamMaxRate 170788
NewUpstreamNoiseMargin 90
NewDownstreamNoiseMargin 60
NewUpstreamAttenuation 150
NewDownstreamAttenuation 170
NewATURVendor 41564d00
NewATURCountry 0400
NewUpstreamPower 486
NewDownstreamPower 514
This is not an array.
To extract the value I want I make:
ATTUPSTREAM=$(echo "$DSLTATE" | awk '{for (I=1;I<NF;I++) if ($I == "NewUpstreamAttenuation") print $(I+1)}')
In this example the value should be 150 but it's always empty.
The weird thing is that I can extract all the values from the same variable with the same command with the exception of the one of the example. If I execute the same command on terminal it works, in the script is not working.
Here an extract of the script:
UPSTREAM=$(echo $DSLSTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewUpstreamCurrRate") print $(I+1)}')
DOWNSTREAM=$(echo $DSLSTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewDownstreamCurrRate") print $(I+1)}')
ATTUPSTREAM=$(echo $DSLTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewUpstreamAttenuation") print $(I+1)}')
ATTDOWNSTREAM=$(echo $DSLSTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewDownstreamAttenuation") print $(I+1)}')
SNRUPSTREAM=$(echo $DSLSTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewUpstreamNoiseMargin") print $(I+1)}')
SNRDOWNSTREAM=$(echo $DSLSTATE | awk '{for (I=1;I<NF;I++) if ($I == "NewDownstreamNoiseMargin") print $(I+1)}')
These are the results:
ATTUPSTREAM=
ATTDOWNSTREAM=170
SNRUPSTREAM=40
SNRDOWNSTREAM=50
Maybe there is some strange character in the DSLSTATE variable in the spacing between the values?
Hoping someone can enlighten me.
Don't use all upper case names for awk or non-exported shell variables to avoid clashing with builtin variables and other reasons, e.g. see Correct Bash and shell script variable capitalization for the shell issues.
You don't need to loop looking for a tag (name) when the input is always in tag-value pairs.
When you have common code put it in a function, don't repeat it multiple times - for all we know there could be a control char or other issue in the code for that one tags value.
Start by changing your code to use a simple lookup function:
$ tag2val() { echo "$DSLSTATE" | awk -v tag="$1" '$1==tag { print $2 }'; }
$ tag2val NewDataPath
Fast
$ tag2val NewUpstreamAttenuation
150
and then let us know if you still have a problem. If you do then edit your question to show the output of echo "$DSLSTATE" | cat -Ev
.