1

hi in this simple script I call a function usage() if there is a cron job owned by root. Is it possible to do an else statement within the awk, so when the condition is not met I call another function? Can you please provide an example? Thx

usage ()
{
# Print usage
       echo "usage function"
} 
#

export -f usage
ps -ef | awk '{if ($0 ~ /crond/ && $1 == "root") {system("/usr/bin/env bash -c usage")
3
  • Hi. You should realize that your awk script NOT ONLY calls a function IF there is a cron job owned by root -- The usage function is called FOR every running root process having the string crond in any part of its command line (a root process as echo crond will cause to call the function usage) Commented Nov 17, 2014 at 18:46
  • About your question: do you know the ELSE clause in awk? Commented Nov 17, 2014 at 18:47
  • If you have a question about assigning variables (as per the question title), would you elaborate on it in the body of the question? Commented Nov 17, 2014 at 18:53

2 Answers 2

1

Yes, awk does allow else statements. In the general form, the if statement looks like this:

if ( conditional ) statement [ else statement ]

As an example:

awk '{if ($0 ~ /crond/ && $1 == "root") system("/usr/bin/env bash -c usage"); else print "None such."}'
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using functions, you should create some scripts that can be callable from within awk. I don't think you can use bash function like this.

See https://unix.stackexchange.com/questions/72935/using-bash-shell-function-inside-awk

1 Comment

I tested his code with the bash function and it works for me. Normally system calls the default shell which might not support it. The OP's system call, however, explicitly runs bash and that seems to work.

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.