Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "if 0;" not work in shell scripting?

I wrote the following shell script, just to see if I understand the syntax to use if statements:

if 0; then
        echo yes
fi

This doesn't work. It yields the error

./iffin: line 1: 0: command not found

what am I doing wrong?

like image 720
MYV Avatar asked Dec 12 '22 14:12

MYV


2 Answers

use

if true; then
        echo yes
fi

if expects the return code from a command. 0 is not a command. true is a command.

The bash manual doesnt say much on the subject but here it is: http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

You may want to look into the test command for more complex conditional logic.

if test foo = foo; then
        echo yes
fi

AKA

if [ foo = foo ]; then
        echo yes
fi
like image 69
Philip Couling Avatar answered Feb 02 '23 15:02

Philip Couling


To test for numbers being non-zero, use the arithmetic expression:

 if (( 0 )) ; then
     echo Never echoed
 else
     echo Always echoed
 fi

It makes more sense to use variables than literal numbers, though:

count_lines=$( wc -l < input.txt )
if (( count_lines )) ; then
    echo File has $count_lines lines.
fi
like image 33
choroba Avatar answered Feb 02 '23 14:02

choroba