user3353393 user3353393 - 1 year ago 88
Bash Question

BASH - simple if statements dont work

Script look like this:

echo -e ""
read text

if [[ $text > 0 && $text < 3 ]]; then
if[ $text == "0" ];
echo "Number is 0"
echo "Number is odd"
echo "You entered: $text"

I have error:

./ line 11: syntax error near unexpected token
./ line 11:

Any ideas what I'm doing wrong I want make simple If in other If statement

Answer Source


if[ $text == "0" ];


if [ $text == "0" ];

As bash sees it, the former statement is an attempt to execute the command if[ with arguments $text, ==, "0", and ]. Since if[ is not if, it does not recognize that line as the start of an if statement. Hence, the then which follows is "unexpected."

Aside on the test command

By the way, you are using both the older [ and the more modern [[ forms of the test command. If you are new to bash, you may want to stick to the [[ syntax because it offers fewer surprises. The only advantage of the older [ form is that it offers compatibility with other shells, particularly dash which is the default /bin/sh on debian-like systems.

There are some surprises, though, with both forms. For one, < and > are not numeric comparison. Instead, both, as man bash explains, "sort lexicographically using the current locale." Thus, under my locale for example, the following statement returns true

[[ -1 > 0 ]]

If you want to do a numeric comparison, use the operator -gt for greater than. Thus, the following returns false:

[[ -1 -gt 0 ]]

The other numeric comparison operators are -eq, -ne, -lt, -le, and -ge.

For more discussion of [ and [[, see Greg's BashFAQ.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download