从外壳脚本函数返回单个值
-
01-10-2019 - |
题
例子:
#!/bin/sh
a() {
R=f
ls -1 a*
[ "$?" == "1" ] && { R=t; }
echo $R
}
r=`a`
echo $r
$r
包含 t
或者 f
但也是输出 ls
命令。
我可能会写 ls -1 a* >/dev/null 2>/dev/null
, ,但是如果有一个更复杂的脚本可能导致错误。
有什么方法可以从 a()
?
解决方案
外壳功能可以返回数字值。考虑0和1,而不是“ F”和“ T”
#!/bin/sh
a() {
R=0
ls -1 a*
[ "$?" == "1" ] && { R=1; }
return $R
}
a
r=$?
echo $r
这仍然会从 ls -1 a*
您可能仍然想处置它,但是 r
将是0或1,不包括输出。
从线或整个块中重定向输出的其他示例是好的,正如其他人建议的那样,您应该知道其他测试条件的方法(但是我假设是 ls
是一个任意的例子)
其他提示
您不必使用 ls
检查以开始的文件 a
. 。只需使用外壳
a() {
shopt -s nullglob
ret="f"
for file in a*
do
ret="t"
break
done
echo "$ret"
}
您可以在命令列表中重定向:
{ command1 command2 } >/dev/null
如果在脚本中的某个时刻您不需要从后续命令中输出任何输出,则可以将Shell的输出重定向 exec
内置:
echo interesting exec >/dev/null echo boring
请注意,这会持续到脚本的末尾,不仅是函数的末尾。这要照顾好有趣的命令,但以前却没有。
有一种方法可以恢复 exec /dev/null
, ,通过使用文件描述符操作。不过,我不一定推荐它,因为在实践中锻炼可能很棘手。这个想法是将连接到标准输出的任何内容重新定位到其他描述符,然后将标准输出重定向到另一个文件,最后将原始标准输出重新放回标准输出。
{ exec 3>&1 # duplicate fd 3 to fd 1 (standard output) exec >/dev/null # connect standard output to /dev/null echo boring exec 1>&3 # connect standard output back to what was saved in fd 3 echo interesting exec >/dev/null # connect standard output to /dev/null again echo more boring } 3>/dev/null # The braced list must have its fd 3 connected somewhere, # even though nothing will actually be written to it.
a() {
ls -1 a* > /dev/null
[ "$?" == "0" ] && echo t || echo f
}
r=`a`
echo $r
考虑使用[-f文件名]和其他文件测试。
不隶属于 StackOverflow