Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using if and a boolean function in bash script: if condition evaluates to false when function returns true

Tags:

function

bash

is_dir_empty(){

    for file in "$1"
    do
        if [ "$file" != "$1" ]; then
            return 0
        fi
    done
    echo "return 1"
    return 1
}

file="/home/tmp/*.sh"

if is_dir_empty "$file"; then
    echo "empty"
else echo "not empty"
fi

it outputs

return 1
not empty

so is_dir_empty returned 1 but if condition evaluated to false somehow.... why?

like image 432
user121196 Avatar asked Feb 05 '13 01:02

user121196


People also ask

What is an IF statement in Bash?

IF statements and their syntax. IF statements are used in making decisions in bash scripting. When an IF statement is introduced in a bash script, it is intended to check for certain conditions before running different commands in the script.

When to use Boolean operators in bash scripts?

When creating complex or multi-conditional tests, that's when to use these Boolean operators. That is to say, if you're writing a bash script where two or more tests will have to return "True", then you have to use &&.

What is Bash If in C++?

Bash IF. Bash IF statement is used for conditional branching in the sequential flow of execution of statements.

What are the different types of if condition in shell script?

Types of if condition in shell script 1. Simple if statement In this type of statement, only the if condition is used, which essentially means that the... 2. If-Else condition This type of statement is used when the program needs to check one condition and perform a task if... 3. If elif else fi ...


Video Answer


1 Answers

Because shell scripts follow the Unix convention of expecting utilities to return zero for success and non-zero for failure, so boolean conditions are inverted.

like image 199
Michael Day Avatar answered Nov 14 '22 21:11

Michael Day