0

I am trying to run the same awk command from the script but I get an extra false I am not sure were it is coming from However when i run the command from terminal it does not return false ?

get_state.sh

#/bin/bash

# sed -n '/\\State/{getline; print}' /var/opt/BESClient/besclient.config
export SERVER_STATE=`awk '/\\State/{getline; print $3}' /var/opt/BESClient/besclient.config`
echo $SERVER_STATE
echo $SERVER_STATE
exit 0

Output

./get_state.sh

false Live
false Live

but

sh-4.1$ awk '/\\State/{getline; print $3}' /var/opt/BESClient/besclient.config

Output

Live
2
  • 1
    why is that an issue ? I am not sure why the false is being printed I am expecting only Live Commented Mar 25, 2015 at 14:59
  • I didn't look closely enough. I assumed you were asking about the duplication. Sorry. Commented Mar 25, 2015 at 15:02

2 Answers 2

1

Backslashes need to be escaped in backticks, and some shells also require $ to be escaped in them. Either do that:

#                            vv-- here --------------v
export SERVER_STATE=`awk '/\\\\State/{getline; print \$3}' /var/opt/BESClient/besclient.config`

Or use $() instead:

export SERVER_STATE=$(awk '/\\State/{getline; print $3}' /var/opt/BESClient/besclient.config)

The false comes from the third field of the line after the line that contains State (but not \State), and that they appear on a single line instead of two is because $SERVER_STATE is unquoted in

echo $SERVER_STATE
Sign up to request clarification or add additional context in comments.

1 Comment

I was beginning to think about whether DOS newlines could be the problem here but this sounds more plausible. Good catch.
0

getline should only be used in a few situations, this not being one of them. In your specific case if \State was the last line of the file or getline failed in any other way then you'd print whatever was the 3rd field of THAT line instead of the subsequent line, and there are various other gotchas. See http://awk.info/?tip/getline for more info.

The way to write your script in awk and call it from shell is:

export SERVER_STATE=$(awk 'f{print $3;f=0} /\\State/{f=1}' /var/opt/BESClient/besclient.config)
echo "$SERVER_STATE"

Note that it doesn't appear to be necessary to export your shell variable and if that's the case then it shouldn't be all-upper-case. Though the variable doesn't appear to be necessary at all so idk what you do with it next...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.