Reputation: 203
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
Upvotes: 0
Views: 920
Reputation: 7287
IMHO if..else redundant here. Use your function like this:
file_exists $FILENAME && echo ok || echo notok
Upvotes: -1
Reputation: 425
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" ]
}
Upvotes: 3