OGIOS

personal website.


Table of contents

Linux shell boolean and cmd exit code

Stuffs like if and while in shell scripts is not work as what we normally think(boolean).
They are actually bind with exit code of a program.

true -> exit code 0
false -> exit code not 0

You can get the code with $? after a command exits:

true # or [[ -1 -gt 0 ]]
echo $?    #`true` is interpreted as a cmd, and exit code is 0
# result: 0

false # or [[ 1 -gt 0 ]]
echo $?
# result: 1

That means you can do commands in places for if or while as long as the command exit normally.

# example
cat "$1" | while IFS= read -r last; do echo $?; done
# read always exit with code 0 until there so no content in anonymous pipe