我想写一个bash函数,检查文件是否具有某些属性并返回true或false。然后我可以在我的脚本中的“如果”中使用它。但是我应该返回什么呢?
function myfun(){ ... return 0; else return 1; fi;}
然后我这样使用它:
if myfun filename.txt; then ...
当然这行不通。如何才能做到这一点呢?
我想写一个bash函数,检查文件是否具有某些属性并返回true或false。然后我可以在我的脚本中的“如果”中使用它。但是我应该返回什么呢?
function myfun(){ ... return 0; else return 1; fi;}
然后我这样使用它:
if myfun filename.txt; then ...
当然这行不通。如何才能做到这一点呢?
当前回答
myfun(){
[ -d "$1" ]
}
if myfun "path"; then
echo yes
fi
# or
myfun "path" && echo yes
其他回答
用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
Edit
从@amichair的评论来看,这些也是可能的
isdirectory() {
if [ -d "$1" ]
then
true
else
false
fi
}
isdirectory() {
[ -d "$1" ]
}
myfun(){
[ -d "$1" ]
}
if myfun "path"; then
echo yes
fi
# or
myfun "path" && echo yes
在只使用选项-d检查目录时要小心! 如果变量$1为空,检查仍然会成功。当然,还要检查变量是否为空。
#! /bin/bash
is_directory(){
if [[ -d $1 ]] && [[ -n $1 ]] ; then
return 0
else
return 1
fi
}
#Test
if is_directory $1 ; then
echo "Directory exist"
else
echo "Directory does not exist!"
fi
继@Bruno Bronosky和@mrteatime之后,我建议你只写布尔返回“向后”。我的意思是:
foo()
{
if [ "$1" == "bar" ]; then
true; return
else
false; return
fi;
}
这样就消除了每个return语句都需要两行代码的丑陋要求。
我发现测试函数输出的最短形式是简单的
do_something() {
[[ -e $1 ]] # e.g. test file exists
}
do_something "myfile.txt" || { echo "File doesn't exist!"; exit 1; }