我想写一个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

其他回答

在只使用选项-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

重写一下可能有用 函数myfun(){…返回0;否则返回1;Fi;}作为这个函数myfun(){…返回;其他假;fi;}。也就是说,如果函数中的最后一条指令为false,则整个函数的结果为false,但无论如何都会返回结果为true的中断函数。我相信至少对我的bash解释器来说是这样的。

我遇到了一个问题(没有明确提到吗?)也就是说,不是如何返回布尔值,而是如何正确地计算它!

我想说的是如果[myfunc];然后……,但这是完全错误的。你不能使用括号!如果myfunc;然后……就是这样做的。

正如@Bruno和其他人重申的那样,真和假是命令,而不是值!这对于理解shell脚本中的布尔值非常重要。

在这篇文章中,我解释并演示了使用布尔变量:https://stackoverflow.com/a/55174008/3220983。我强烈建议你去核实一下,因为它们是如此密切相关。

在这里,我将提供一些从函数返回和计算布尔值的示例:

这样的:

test(){ false; }                                               
if test; then echo "it is"; fi                                 

不产生回声输出。(即false返回false)

test(){ true; }                                                
if test; then echo "it is"; fi                                 

生产:

it is                                                        

(即true返回true)

And

test(){ x=1; }                                                
if test; then echo "it is"; fi                                 

生产:

it is                                                                           

因为0(即true)是隐式返回的。

现在,这就是把我搞砸的事情……

test(){ true; }                                                
if [ test ]; then echo "it is"; fi                             

生产:

it is                                                                           

AND

test(){ false; }                                                
if [ test ]; then echo "it is"; fi                             

还生产:

it is                                                                           

在这里使用括号会产生假阳性!(我推断“outer”命令的结果是0。)

从我的帖子中得到的主要信息是:不要像典型的相等检查那样使用括号来计算布尔函数(或变量),例如if [x -eq 1];然后……!

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" ]
}