Search code examples
bashpipestatus

How set an exit code when exiting bash?


I want to run a command from a sub-bash and I need the return code from it; actually it's running a pipeline and I need the PIPESTATUS array, or at least one component.

This was my best guess and it does not work. I just get a 0. Since bash did not error it makes sense, it's just not what I need. Help?

bash -c "echo 123 | grep abc | sort; exit ${PIPESTATUS[1]}"; echo $?
0

Solution

  • Try with single quotes:

    bash -c 'echo 123 | grep abc | sort; exit ${PIPESTATUS[1]}'; echo $?
    

    Sample runs:

    bash -c 'echo 123 | grep abc | sort; exit ${PIPESTATUS[1]}'; echo $?
    1
    
    bash -c 'echo 123 | grep abc | sort; echo status is ${PIPESTATUS[@]}'; echo $?
    status is 0 1 0
    0
    

    There is a related post on this.