0

I have a bash script (test.sh) with the following:

#!/bin/bash

npm test |& grep -v '[HPM]'

if [[ $? -ne 0 ]]; then
...

When trying to run this script locally I get this error:

test.sh: line 3: syntax error near unexpected token `&'
test.sh: line 3: `npm test |& grep -v '[HPM]''
7
  • Are you just running the script like ./test.sh? Commented Apr 9, 2021 at 15:47
  • 3
    Don't use the |& syntax. Your life will be much easier if you use npm test 2>&1 | grep ... Commented Apr 9, 2021 at 15:48
  • ...and your life will be even easier if you do npm test | grep and don't modify stderr. Commented Apr 9, 2021 at 15:49
  • No @0x5453. Doing sh test.sh. Whenever I try ./test.sh it says no such file or directory. Commented Apr 9, 2021 at 15:53
  • 4
    Well, that's why. |& is bash syntax, not sh. Commented Apr 9, 2021 at 15:56

1 Answer 1

1

The |& syntax is using a non-standard token which is recognized by bash but not all shells. Such a construct is often called a bashism. If your shell is inadvertently invoked as a non-bash shell, then it is a syntax error. You can easily use a standardized construct for this:

npm test 2>&1 | grep -v '\[HPM\]' 

Note that this is unusual. It seems odd to capture the stderr of npm, but perhaps you really do want to check if grep prints any lines. There's really no need to explicitly check $?, and your code would normally be written:

if ! npm test 2>&1 | grep -v '\[HPM\]'; then
    : grep failed.  Do something 
fi

But again, this seems strange. grep -v will "fail" if it does not print any lines of text, and it will succeed otherwise. Perhaps you were expecting $? to contain the exit status of npm in your original code, but it does not. $? will be zero if grep prints any text, and non-zero otherwise.

Sign up to request clarification or add additional context in comments.

3 Comments

npm test starts a server and then runs integration tests. In some instances, [HPM] errors are printed in the terminal. To hide these errors, I am using 2>&1 | grep -v '[HPM]'. Do you have any other suggestions as to hide these errors? Also, answering your question about $?, I am expecting it to contain the exit status of npm test ... but youre right that it does not. Do you know how I could check the exit status of npm test?
You could do: if ! npm test; then ...; fi 2>&1 | grep -v '[HPM]', but that gets a little clumsy with any other errors. Probably better to do something like { if ! npm test; then ....; fi 2>&1 >&3 | grep -v '[HPM]' >&2; } 3>&1...but really it's best to not try to filter the HPM errors! Fix them instead.
Also note that grep -v '[HPM]' will also filter the line the just contains H. You probably meant grep -v '\[HPM\]'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.