测试文件是否在shell脚本中具有函数功能

问题描述 投票:0回答:1

我有以下脚本,基本上是一个函数和一个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,但我不明白为什么它不起作用

linux bash shell
1个回答
1
投票

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

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

with

if file_exists "LICENSE"; then

关于0=true1=false的约定,它是not preferred to write them out explicitly in return statementsfile_exists函数的主体可以简化为

file_exists() {
    [ -f "$1" ]
}
© www.soinside.com 2019 - 2024. All rights reserved.