可以让awk退出一个带有`exit 2`的bash脚本吗?

时间:2018-05-25 14:30:40

标签: linux bash awk

根据awk脚本中的某些条件,我需要从awk脚本中获取退出代码并将其传递给bash脚本,因此它可以退出,例如: exit 2

如果我从awk拨打system("exit 2"),则bash脚本仍会以0退出。

问题

如何从awk到bash脚本获取$code的值?

#!/usr/bin/bash

# ...

awk '{
  # ...
  code=2
  # ...
}' /proc/loadavg

exit $code

3 个答案:

答案 0 :(得分:5)

以下是一个示例shell脚本:

awk -v code="2" 'BEGIN{exit code}'
shell_code=$?
echo $shell_code #just for seeing the code
exit $shell_code

上面的shell脚本将退出2,即awk的变量code

中的值

awk单行也可以输入文件,例如:

awk 'BEGIN{code=2} {if (something happens) exit code}' file

但是我认为你可以让awk输出一些值而不是exiting一个值。然后将此awk输出分配给shell变量。您可以在shell脚本中决定是否要退出具有哪个值的shell脚本,直到awk输出。

答案 1 :(得分:2)

awk '{
       # ...
       # default value of code will be 0, no need to declare...
       # if something went wrong set
       code=2
       # if you need to terminate, uncomment next line
       # exit
       # otherwise processing will continue
       # ensure you don't overwrite code
     }
 END {exit code}
' /proc/loadavg

答案 2 :(得分:2)

using integer = int64_t;

integer factorial(integer number) {
    return number <= 0 ? 1 : number * factorial(number - 1);
}

integer binomial_coefficent(integer n, integer r) {
    return factorial(n) / (factorial(r) * factorial(n - r));
}

int main()
{
    using namespace std;
    cout << binomial_coefficent(40, 20) << endl;
    return 0;
}