我想写一个bash函数,检查文件是否具有某些属性并返回true或false。然后我可以在我的脚本中的“如果”中使用它。但是我应该返回什么呢?

function myfun(){ ... return 0; else return 1; fi;}

然后我这样使用它:

if myfun filename.txt; then ...

当然这行不通。如何才能做到这一点呢?


当前回答

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

其他回答

在只使用选项-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(){
    [ -d "$1" ]
}
if myfun "path"; then
    echo yes
fi
# or
myfun "path" && echo yes

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

我发现测试函数输出的最短形式是简单的

do_something() {
    [[ -e $1 ]] # e.g. test file exists
}

do_something "myfile.txt" || { echo "File doesn't exist!"; exit 1; }

出于代码可读性的考虑,我认为返回true/false应该:

在一条线上 成为一个命令 容易记住 提到关键字return后跟另一个关键字(真或假)

我的解决方案是返回$(true)或返回$(false)如下所示:

is_directory()
{
    if [ -d "${1}" ]; then
        return $(true)
    else
        return $(false)
    fi
}