-1

two commands with OR condition

test -e a.txt || test -e b.txt this command running without any problem from CLI but if I read from a file and try to run it gives sh: ||: unknown operand' error

cat test.txt
test -e a.txt  || test -e b.txt

Read and Run the command

cat test.txt| while read command; do $command;done

sh: ||: unknown operand

Any thoughts

Kenot Solutions
  • 377
  • 1
  • 4
  • 11
  • 1
    Read this article: [I'm trying to put a command in a variable, but the complex cases always fail!](https://mywiki.wooledge.org/BashFAQ/050) – M. Nejat Aydin Jul 16 '20 at 00:44
  • @KenotSolutions: Also, as you see from the error message (_**sh**: ||: unknown operand_), you are not running bash. I suggest that you replace the _bash_ tag by either the _shell_ tag or the _sh_ tag. – user1934428 Jul 16 '20 at 06:14

1 Answers1

1

Very simplified, bash will:

  1. Parse a command or structure, then for each command:
  2. Apply brace expansion
  3. Apply parameter expansion
  4. Do word splitting
  5. Apply pathname expansion
  6. Execute the result

Handling of || happens during parsing in step 1, but you expand it in step 3. As a result, it's treated as a regular string as if running test -e a.txt "||" test -e b.txt.

It will similarly fail for commands like echo {1..10} which would require re-doing #2, and echo $PATH which would require re-doing #3.

Meanwhile, it will work for echo Hello (#4) and ls *.png (#4/#5) because these only use features that come after.

While having a command in a string is a code smell indicating that you're painting yourself into an awkward corner, you can use eval to apply all the steps over from #1 on a string of your choice:

cmd="test -e a.txt || test -e b.txt"
eval "$cmd"
that other guy
  • 116,971
  • 11
  • 170
  • 194