首页 > 解决方案 > 使用shell脚本中的函数测试文件是否存在

问题描述

我有以下脚本,基本上是一个函数和一个 IF

file_exists() {

    if [ -f "$1" ]; then
        return 0
    else
        return 1
    fi
}

if [[ $(file_exists "LICENSE") ]]; then
    echo "YES"
else
    echo "NO"
fi

但是这段代码总是返回 NO。我知道 IF 语句期望得到一个 0 为真,但我不明白为什么它不起作用

标签: linuxbashshell

解决方案


在 if 语句中使用函数的返回值时,不需要将其包装在[[]]. 你可以更换

if [[ $(file_exists "LICENSE") ]]; then

if file_exists "LICENSE"; then

至于 and 的约定0=true1=false最好不要在 return 语句中明确地写出来。你的file_exists函数体可以简化为

file_exists() {
    [ -f "$1" ]
}

推荐阅读