从shell脚本函数返回单个值

Pet*_*Mmm 5 shell return-value bash-function

例:

#!/bin/sh

a() {
R=f
ls -1 a*
[ "$?" == "1" ] && { R=t; }
echo $R
}

r=`a`
echo $r
Run Code Online (Sandbox Code Playgroud)

$r包含t或者f也包含ls命令的输出.

我可以写ls -1 a* >/dev/null 2>/dev/null,但如果有一个更复杂的脚本可能导致错误.

有没有办法从单个值返回a()

Ste*_*n P 4

shell 函数可以返回数值。考虑 0 和 1 而不是“f”和“t”

#!/bin/sh

a() {
R=0
ls -1 a*
[ "$?" == "1" ] && { R=1; }
return $R
}

a
r=$?
echo $r
Run Code Online (Sandbox Code Playgroud)

ls -1 a*这仍会写入您可能仍想处理的输出,但 的值r将为 0 或 1,并且不包含输出。

从一行或整个块重定向输出的其他示例都很好,并且正如其他人所建议的那样,您应该了解测试条件的其他方法(但我假设这是ls一种任意的示例)