M
M
Marcel Markhabulin2011-06-21 14:52:41
bash
Marcel Markhabulin, 2011-06-21 14:52:41

bash. Why if [ 0 ] is true and if [ 1 ] is false?

Due to certain circumstances, it is necessary to write a bash script. Previously, I wrote it in C, PHP.
In php, such a construction will be executed correctly, because 0 is nothing / nothing (but 0 is not NULL, although it will not be executed with a NULL if result), and 1 will be executed anyway, because 1 is something existing (a number or a string) and not is "nothing".

I got to the bottom of this in the wrong handling of nested if loops (nested loops were always executed, regardless of what I set as a condition. For example, the conditions [ 1>2 ] and [ let "3<2" ] are always true and run nesting then

I found a similar mention here , where the most interesting clipping is:
#!/bin/bash
if [ 0 ] # ноль
then echo "0 -- это истина."
else echo "0 -- это ложь."
fi
# 0 -- это истина.

if [ 1 ] # единица
then echo "1 -- это истина."
else echo "1 -- это ложь."
fi
# 1 -- это ложь.

if [ -1 ] # минус один
then echo "-1 -- это истина."
else echo "-1 -- это ложь."
fi
# -1 -- это истина.


In normal manuals it is described why conditions return this or that result. I could not find a description of why this is the logic of work. Why is this happening?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
afiskon, 2011-06-21
@afiskon

In short - in modern operating systems, if the program completes successfully, it returns 0, otherwise - an error code that is greater than zero. That's why.

G
Gribozavr, 2011-06-21
@gribozavr

man bash
/test
1 argument
The expression is true if and only if the argument is not null.
$ [ 0 ] && echo true
true
$ [ 1 ] && echo true
true
$ [ -1 ] && echo true
true
$ [ "" ] && echo true
$

A
avatar29, 2014-12-15
@avatar29

if [ 1 ] # one
then echo "1 is true."
else echo "1 is false."
fi
# 1 is false False
, 1 is true.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question