7

I've seen questions regarding the same issue, but all of them are about strings. How about integers? Why am I getting the "unary operator expected" error?

 if [ $(date +%k%M) -ge ${!BLOCK1FRAN} ] ; then whatever ; fi
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paolo
  • 2,161
  • 5
  • 25
  • 32
  • 3
    You are using indirection. If the variable `${BLOCK1FRAN}` points to an empty variable, you'll get the error message. – alvits Apr 01 '14 at 23:09
  • The canonical may be *["unary operator expected" error in Bash if condition](https://stackoverflow.com/questions/13617843/)* – Peter Mortensen Oct 05 '21 at 16:51

2 Answers2

13

You are using indirection. If the variable ${BLOCK1FRAN} points to an empty variable, you'll get the error message. Make sure that the variable pointed by ${BLOCK1FRAN} contains a valid numeric value.

If you want an empty string and nonnumeric values to be evaluated as zero (0), use the following syntax.

if [[ $(date +%k%M) -ge ${!BLOCK1FRAN} ]]; then whatever ; fi
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alvits
  • 6,550
  • 1
  • 28
  • 28
  • 2
    +1 Another approach: Declare names in bash you expect to be numeric to have the integer attribute. This gives a semblance of indirection, but also guarantees the value will be numeric. `declare -i x BLOCK1FRAN; BLOCK1FRAN=x; echo $BLOCK1FRAN` – kojiro Apr 02 '14 at 01:07
  • Double brackets instead of singles ones seem to work well, thank you. May I ask why this is? And why would anyone choose to use [ instad of [[? – Paolo Apr 04 '14 at 19:59
  • The main difference between `[ and ]` and `[[ and ]]` is that word splitting and pathname expansion are not performed on the latter. For example, if you have `*` within `[ and ]`, it will be expanded to the files in the `$PWD` whereas the same `*` inside `[[ and ]]` won't. And most likely you intend to use the literal `*`. For more details see `bash` manpage. – alvits Apr 04 '14 at 20:09
-1

It looks good to me. Are you sure you've set BLOCK1FRAN correctly?

whatever() { echo "it works"; }
foo=42
BLOCK1FRAN=foo
if [ $(date +%k%M) -ge ${!BLOCK1FRAN} ] ; then whatever ; fi

it works
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
that other guy
  • 116,971
  • 11
  • 170
  • 194