0
soham@zcon-63:~$ _OPTION_START_DATETIME=""
soham@zcon-63:~$ _OPTION_END_DATETIME=""
soham@zcon-63:~$ [ -n "${_OPTION_START_DATETIME}"]
soham@zcon-63:~$ echo $?
0
soham@zcon-63:~$ [ -n "${_OPTION_END_DATETIME}"]
soham@zcon-63:~$ echo $?
0
soham@zcon-63:~$ [ -n "${_OPTION_START_DATETIME}"] && [ -n "${_OPTION_END_DATETIME}" ]
soham@zcon-63:~$ echo $?
1
soham@zcon-63:~$

In shell, if a condition is true then the output is zero(0). My expectation of binary operation true logical and true is true(0). But unexpectedly I am getting the output as false(1).

Cyrus
  • 69,405
  • 13
  • 65
  • 117
Soham Lawar
  • 694
  • 8
  • 16
  • 3
    You need a space before the closing `]`. – Benjamin W. Nov 16 '18 at 05:55
  • 1
    $? will not tell you if the condition is true or false. it will just tell you if the previously executed command is successfully executed or not. Even if the condition fails and the command execution is successful then it will return true. – Sekar Ramu Nov 16 '18 at 06:35

1 Answers1

1

As @BenjaminW said in a comment, you need a space before the closing ]. Without that, the string "${_OPTION_START_DATETIME}"] is treated as a single shell "word", part of which happens to be quoted. Since the variable is blank, it's equivalent to ""], which is equivalent to just ]. Thus, the entire command becomes:

[ -n ]

... and since there's only one argument between the [ and ], the test applied is "is that single argument blank?". That is, -n is treated as a string to be checked for existence rather than an operator. "-n" is not blank, so the test evaluates to true.

Here and in many other places, spaces are absolutely critical pieces of shell syntax. There are a few places where spaces are optional, but in most places they cannot be either added or left out without changing the meaning of the command (or causing a syntax error).

Gordon Davisson
  • 95,980
  • 14
  • 99
  • 125