I have an individual.sh script that pipes standard error to a grep command, like this:

FOUND=$(tesseract "$i" out -psm 0 |& grep -ci 'Orientation in degrees: [^0]')

If I run the script like this I have no problems ./individual.sh filename

But I want to pipe a bunch of files into the script. I am using this command to do so:

find corpus/ -type f -exec ./individual.sh {} \;

which is throwing this error from the line in individual.sh that redirects standard error.

./individual.sh: 7: ./individual.sh: Syntax error: "&" unexpected

How do I redirect standard error while using the find -exec option

  • 1
    What kind you shell you using? - try ps $$ to figure out Does you shell script contains the #!/bin/bash (in case if your shell is bash) in the first line. In posix shell you should use cmd1 2>&1 | grep something
    – gena2x
    Oct 24 '14 at 16:59
  • You would never have had that problem if you had just done cmd1 2>&1 | cmd2. fancy implementation-dependent syntax like |& is fine and good for interactive shells, but when scripting if you make it a habit to observe portability wherever possible, you might find you do a lot less debugging.
    – mikeserv
    Oct 25 '14 at 15:48

Maybe you're using zsh. Try adding as the first line of the file, #!/usr/bin/zsh.

  • 1
    Afsin may have it right. |& is only supported on bash 4+ and zsh. Which shell and version are you using to execute the find command, and do you have a shebang (#!/bin/bash for example) at the top of your individual.sh script? Oct 24 '14 at 17:27
  • @Omnipresence yeah, adding the shebang fixed it. Why is that? Can you explain?
    – bernie2436
    Oct 24 '14 at 17:40
  • I only have a guess. I am going to assume you're using bash greater than 4 (you can confirm with bash --version) but you're using something something else as your shell (ksh maybe, check using ps $$ as gena2x mentioned). Before you started using find (in your previous question), you'd been using run.sh with a for loop. That run.sh has a #!/bin/bash at the start, so when individual.sh was run, you were already in a bash shell. Now that you're using the find command, individual.sh is executed in whatever shell you're already in, unless you change it with a #! Oct 24 '14 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.