简体   繁体   English

使用awk调用功能和命令

[英]invoking function and command using awk

Hi this script works fine, it calls the function when there a cronjob running under root 嗨,这个脚本工作正常,当在root下运行cronjob时,它将调用该函数

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

export -f usage
ps -ef | awk '{if ($0 ~ /crond/ && $1 == "root") {system("/usr/bin/env bash -c usage") }}'

However, in addition to calling the function I also like to print $2 or just call a second command. 但是,除了调用该函数外,我还喜欢打印$ 2或仅调用第二个命令。 I cannot get the syntax right. 我无法正确使用语法。 Can someone help please. 有人可以帮忙吗。 in short, how do you run multiple commands when the condition is met? 简而言之,当满足条件时如何运行多个命令? In the example above, in addition to running the usage() function I also like to run a second function and also print $2 ( which is the process ID ). 在上面的示例中,除了运行usage()函数之外,我还希望运行第二个函数并打印$ 2(这是进程ID)。 Thanking you all in advance 提前谢谢大家

For Bash, you can use ; 对于Bash,可以使用; or && to chain together commands. &&将命令链接在一起。

; is used to separate commands, but does not check the error code of the previous command. 用于分隔命令,但不检查前一个命令的错误代码。 eg dddate; echo 'hi' 例如dddate; echo 'hi' dddate; echo 'hi' will echo 'hi', even though "dddate" likely returns an error. 即使“ dddate”可能返回错误, dddate; echo 'hi'也将回显“ hi”。

&& will only run the latter command if the previous command doesn't throw an error. &&仅在前一个命令没有引发错误时才运行后一个命令。 eg dddate && echo 'hi' will not run the echo command because dddate failed. 例如dddate && echo 'hi'将不会运行echo命令,因为dddate失败。

For your usage, you could make: 对于您的用法,您可以进行以下操作:

system("/usr/bin/env bash -c usage") into system("/usr/bin/env bash -c usage); print $2" . system("/usr/bin/env bash -c usage")放入system("/usr/bin/env bash -c usage); print $2"

root@debian:~# ps -ef | awk '{if ($0 ~ /crond/ && $1 == "root") {system("/usr/bin/env bash -c usage"); print "hi"}}'
usage function
hi

Try running multiple commands separated by semicolon 尝试运行以分号分隔的多个命令

For example : 例如 :

ps -ef | awk '{if ($0 ~ /crond/ && $1 == "root") {system("/usr/bin/env bash -c usage"); system("/usr/bin/env bash -c func2"); print $2 }}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM