0

I have the following script, basically a function and an IF

file_exists() {

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

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

But this code always returns NO. I know the IF statement expects to get a 0 to be true, but I don't understand why it doesn't work

Renato Tavares
  • 201
  • 1
  • 3
  • 12
  • Also consider `-s` which will test `"True if file exists and has a size greater than zero."` – David C. Rankin Dec 30 '19 at 05:11
  • 1
    Your function does not write anything to stdout. Hence, `$(file_exists.....) is always empty. `[[ '' ]]` (i.e. on an empty string) takes by design the `else` branch. – user1934428 Dec 30 '19 at 07:30

2 Answers2

3

When using the return value of a function in an if-statement, you do not need to wrap it in [[]]. You can replace

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

with

if file_exists "LICENSE"; then

As for the convention of 0=true and 1=false, it's not preferred to write them out explicitly in return statements. The body of your file_exists function can be reduced to

file_exists() {
    [ -f "$1" ]
}
Michael Jarrett
  • 425
  • 3
  • 10
-1

IMHO if..else redundant here. Use your function like this:

file_exists $FILENAME && echo ok || echo notok
Ivan
  • 6,188
  • 1
  • 16
  • 23