0

It is quite straightforward to check if a single command returned exit code 0. However, I'm not sure what to do if I use echo with a command. For example, in this case, program I want to test definitely returns non-zero exit code, but it looks like bash looks at echo's exit code instead, which is 0:

    if echo "something" > exit 42; then
        echo "OK"
    else
        echo "NOT OK"
    fi

It makes impossible to check if a program which requires interactive input returned non-zero exit code. How can I fix that and get the exit code of the program I'm echoing something to?

keddad
  • 423
  • 1
  • 3
  • 10

1 Answers1

0

It turns out that bash does exit just fine. The problem was that if echo "something" > exit 42; then just printed "something" to file called exit instead of running exit, so the return code was actually 0. To fix that, you should use "|". if echo "something" | exit 42; then works as expected.

keddad
  • 423
  • 1
  • 3
  • 10
  • 2
    Actually, it should have printed `something 42` to the file called `exit`. The position of a simple redirect doesn't usually matter – roaima Feb 13 '22 at 20:24
  • 2
    `echo "something" | exit 42` is bad code, because `exit` doesn't expect anything on _stdin_, and the output from `echo` is lost. The correct construct would simply be two commands: `echo 'something'; exit 42`. However, I'm still not at all sure what you're trying to achieve with your original piece of code – roaima Feb 13 '22 at 23:18