从 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代表真,1代表假.
示例:
#!/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屋!
查看全文