从Bash函数返回布尔值 [英] Returning a boolean from a Bash function
本文介绍了从Bash函数返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个bash函数,该函数检查文件是否具有某些属性并返回true或false.然后,可以在脚本中的"if"中使用它.但是我应该返回什么?
I want to write a bash function that check if a file has certain properties and returns true or false. Then I can use it in my scripts in the "if". But what should I return?
function myfun(){ ... return 0; else return 1; fi;}
然后我像这样使用它:
if myfun filename.txt; then ...
这当然是行不通的.如何做到这一点?
of course this doesn't work. How can this be accomplished?
推荐答案
将0表示为true,将1表示为false.
Use 0 for true and 1 for false.
示例:
#!/bin/bash
isdirectory() {
if [ -d "$1" ]
then
# 0 = true
return 0
else
# 1 = false
return 1
fi
}
if isdirectory $1; then echo "is directory"; else echo "nopes"; fi
修改
在@amichair的评论中,这些也是可能的
From @amichair's comment, these are also possible
isdirectory() {
if [ -d "$1" ]
then
true
else
false
fi
}
isdirectory() {
[ -d "$1" ]
}
这篇关于从Bash函数返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文