Matt
Matt

Reputation: 1032

Using shell command in awk not working

I have the following code in shell.

It does not work. So I don't know what's my mistake I was wondering if someone could help me

echo $i | awk -F "," '{if(NF == 1) print "Exiting..." system("exit")}'

so $i is a parameter for example hi,hello. And if the number of fields is equal to 1, I'd like the program to exit.

Upvotes: 1

Views: 219

Answers (2)

user000001
user000001

Reputation: 33327

You cannot call exit through system, because awk is executed in a separate process. However, you can call exit from awk, with a specified error code, and then exit the script depending on the error code. Example:

awk -F "," '{if(NF==1){ print "Exiting"; exit -1}}' || exit

Upvotes: 2

tripleee
tripleee

Reputation: 189397

Awk cannot force its parent process to exit, but you can refactor the code so the calling shell exits.

In this limited context, you don't need Awk at all, though.

case $i in
  *,* ) ;; # nothing
  * ) echo Exiting... >&2; exit 1;;
esac

Upvotes: 3

Related Questions