1

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.

3
  • Do you want the script that contains the above code to exit? Since the awk command runs in a different process you cannot exit like this. You could however call the exit command (without system) from awk, with a specific exit code, and then check awk's exit code from the shell script. Commented Oct 21, 2013 at 16:37
  • @user000001 if NF is equal to 1, I want the WHOLE code to exit. Commented Oct 21, 2013 at 16:39
  • @ Matin Added an example for that Commented Oct 21, 2013 at 16:44

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

5 Comments

@Matin It shouldn't exit for NF>1. Perhaps you did not separate the fields with comma (,)? Also note that you forgot a set of curly brackets in the code in your question
i do :( I have my string is --only:4,3,2,1 lots of commas. but it still exits
@Matin Strange... Try echo "1,2,3 " | awk -F "," '{if(NF==1){ print NF "Exiting"; exit -1}}' || exit. I did it on my system and it worked...
it worked The problem was <<< "1" I didn't have to put that
@Matin Yes the <<< "1" is a different way of specifying input redirection when the input is a string (equivalent to echo "1" | ...) If the input comes from another command, then you should not add it.

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.