8

The following works in Ubuntu but not Yocto (Poky).

root@system:~/# x='abc'
root@system:~/# y=''
root@system:~/# [[ $(echo $x) != '' ]] && echo true
true
root@system:~/# [[ $(echo $y) != '' ]] && echo true
sh: : unknown operand

In Ubuntu the last line returns nothing (as expected). Any ideas why it's throwing an error in Yocto?

Trevor
  • 1,111
  • 2
  • 18
  • 30
geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 3
    I'm betting that `sh` is not the same on those two platforms and that on Yocto it's not as fully implemented, I was actually surprised that `sh` implemented `[[` at all, Yocto or otherwise – Eric Renouf Dec 13 '15 at 01:07
  • Ubuntu has dash as sh, while an image built with OpenEmbedded often has busybox as sh. – Anders Dec 13 '15 at 09:13
  • @eric-renouf Any idea exactly what the problem can be though, considering it works in Yocto for `$x`? – geotheory Dec 13 '15 at 12:02
  • 2
    I'm guessing the problem is how it handles "empty" args, so as long as you have a value on each side of `!=` it will work. You might just try quoting the command substitutions like `[[ "$(echo $y)" != '' ]]...` and see if that helps – Eric Renouf Dec 13 '15 at 12:25
  • @EricRenouf That works thanks Eric. Want to add as the answer? – geotheory Dec 13 '15 at 13:02

2 Answers2

14

The problem seems to be that $(echo $y) is expanding to an empty string, and then [[ isn't handling it correctly. The solution to that would be to quote the command substitution like

[[ "$(echo "$y")" != '' ]] && echo true

though it's probably better still to use printf than echo so you might do it as

[[ "$(printf '%s' "$y")" != '' ]] && echo true

just in case $y might end up with special characters that can trip up echo or similar

Community
  • 1
  • 1
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
11

Apparently, busybox ash has a rather simplistic implementation of [[. It is the same as [ except that it expects a ]] instead of ] final argument. This misses the point of why [[ can be useful at all: [[ is supposed to be a keyword with special parsing and using it looks more beautiful and avoids various pitfalls (while adding some of its own). I guess they added it so a few more bash scripts run unmodified on busybox ash.

To avoid confusion, I recommend not using [[ in busybox at all. Use [ and quote all command substitutions and parameter expansions.

jilles
  • 10,509
  • 2
  • 26
  • 39