【问题标题】:Returning a value in a function witch echoes in bash在 bash 中回显的函数中返回值
【发布时间】:2020-10-30 13:12:48
【问题描述】:

我正在尝试创建一个 bash 函数,但该函数必须显示一些消息并返回一个值。 这是一个例子:

#!/bin/bash

function test() {
        echo "Hello"
        return 0
}

if [ $(test) ]; then
        echo "yes"
else
        echo "no"
fi

但如果我执行回显退出,我无法捕获返回值。 这是可能的? 问候

【问题讨论】:

  • btw.:为避免意外,我不会为已分配为内置命令的函数命名。请参阅:type testhelp testhelp help
  • 是的,这只是一个示例代码,将其发布在stackoverflow中

标签: bash function echo return-value


【解决方案1】:

当然可以:if 根据返回状态进行分支,并且将输出分配给变量不会影响返回状态:

if output=$(testFunc); then
  echo "success: $output"
else
  echo "failure: $output"
fi

如果您需要返回值,您可以从 $? 变量中获取:

output=$(foo 0)
rc=$?
if [[ $rc -eq 0 ]]; then        # or `if ((rc == 0))`, an arithmetic comparison
  echo "success: $output $rc"   # $rc will always be 0 here
else
  echo "failure: $output $rc"
fi

【讨论】:

  • 这适用于 0 返回 (ok) 或 0 返回 (ko),但我怎样才能捕获循环值?
猜你喜欢
  • 2023-03-16
  • 2013-06-24
  • 2011-05-21
  • 1970-01-01
  • 2019-09-13
  • 2011-07-22
  • 1970-01-01
  • 2014-01-31
  • 2021-11-24
相关资源
最近更新 更多