0

I want to set a variable in shell to true depending on if certain requirement is met. That requirement is determined by awk.

So here's what I do

$  different=false

$  awk 'if (certain requirements met) {'different=true'}' inputfile

$  if $different; then
     print "Different

However, different does not set to true.

PS my certain requirements met is definitely true.

Thank you

1
  • You may possible use awk for all the test, no need for the extra if test. Commented Nov 5, 2013 at 20:54

2 Answers 2

4

awk cannot set variables in the shell that called it. You can use exit to set awk's exit status:

$ if awk 'if (certain requirements met) {exit 0} else { exit 1 }' inputfile; then
>  printf "different\n"
> fi

Or capture the output of awk in a variable:

$ different=$( awk 'if (certain requirements met) { print "true" } else { print "false" }' inputfile )
$ if [[ $different = true ]]; then
>  printf "different\n"
> else
>  printf "Not different"
> fi
Sign up to request clarification or add additional context in comments.

5 Comments

awk cannot set shell variables in the parent shell. But, I believe awk can set values on variables exported to a child shell.
Thank you. How can I exit awk though? For example if a certain requirement is met, exit awk, meaning ignore the rest of awk code. I do NOT want it to exit the shell code. Just ignore the rest of awk and continue the rest of the code...
awk has its own exit command, which just exits the awk process, not the shell that calls awk.
So I'd just write exit in awk?
Yes, just as I wrote in the answer.
2

Here is how you do it.

different=$(awk 'if (certain requirements met) {print "true"}' infile)

1 Comment

else print "false"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.