0

I'm trying to write a oneliner bash test containing "||"s and "&&"s, here is what it looks like :

$ [ [ $extension = mp4 ] || [ $extension = m4a ] || [ $extension = mp3 ] ] && echo OK || echo KO
bash: [: too many arguments
bash: [: too many arguments
KO
$ set -x
$ [ [ $extension = mp4 ] || [ $extension = m4a ] || [ $extension = mp3 ] ] && echo OK || echo KO
+ '[' '[' mp4 = mp4 ']'
bash: [: too many arguments
+ '[' mp4 = m4a ']'
+ '[' mp4 = mp3 ']' ']'
bash: [: too many arguments
+ echo KO
KO

EDIT : This seems to work :

$ [ $extension = mp4 ] || [ $extension = m4a ] || [ $extension = mp3 ] && echo OK || echo KO
OK
codeforester
  • 39,467
  • 16
  • 112
  • 140
SebMa
  • 4,037
  • 29
  • 39
  • 2
    If you want `&&` and `||` to work, use `[[ ]]`, not `[ ]`; `[[ $foo && $bar && $baz ]]` works fine. – Charles Duffy Apr 04 '19 at 19:53
  • 2
    Alternately, just stop nesting: `[ "$extension" = mp4 ] || [ "$extension" = m4a ] || [ "$extension" = mp3 ]` – Charles Duffy Apr 04 '19 at 19:53
  • 2
    ...or even better, stop using `[` altogether and switch to `case`: `case $extension in mp4|m4a|mp3) echo OK;; *) echo KO;; esac` – Charles Duffy Apr 04 '19 at 19:54
  • 2
    BTW, note that `a && b || c` is **not** identical to `if a; then b; else c; fi`, as described in [BashPitfalls #22](http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3). – Charles Duffy Apr 04 '19 at 19:55
  • As a quick aside -- if you're using `[`, be sure to quote your expansions: `[ "$extension" = mp4 ]` prevents you get from getting syntax errors or other undesired behavior if the extension contains whitespace, expands as a glob, or is otherwise unusual/interesting. BTW, http://shellcheck.net/ will catch a lot of that class of bugs. – Charles Duffy Apr 04 '19 at 21:08

0 Answers0