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?

6
  • 2
    program I want to test definitely returns non-zero exit code - but what program are you testing here? Commented Feb 13, 2022 at 20:04
  • @ArkadiuszDrabczyk here I've added exit just to show that it returns bad exit code and still prints "OK". Originally, it looked like if echo "something" > ./mybinary; then
    – keddad
    Commented Feb 13, 2022 at 20:05
  • 3
    You're not exiting here but redirecting output of echo to a file called exit. Commented Feb 13, 2022 at 20:07
  • @ArkadiuszDrabczyk oh, I see, bash does exit as it should, the problem was that I passed the input incorrectly. Thanks!
    – keddad
    Commented Feb 13, 2022 at 20:09
  • Should I remove the question, or should I post that as an answer?
    – keddad
    Commented Feb 13, 2022 at 20:10

1 Answer 1

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.

2
  • 2
    Actually, it should have printed something 42 to the file called exit. The position of a simple redirect doesn't usually matter Commented Feb 13, 2022 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 Commented Feb 13, 2022 at 23:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .