Booleans and Return Codes
Before we can describe conditionals and loops, we need to explain the concept of a Boolean (true/false) test. A Boolean is an entity that can have the value true or false. A Boolean test simply checks a value to see if it’s true or false. To the shell, the value 0 means true or success, and anything else means false or failure. (Think of zero as “no error” and other values as error codes.)[36]
Every command returns an integer value, called a return
code or exit status, to the shell
when the command exits. You can see this value in the special variable
$?:
➜cat myfileMy name is Sandy Smith and I really like OS X Lion ➜grep Smith myfileMy name is Sandy Smith and A match was found... ➜echo $?0 ...so return code is “success” ➜grep aardvark myfile➜echo $?No match was found... 1 ...so return code is “failure”
The return codes of a command are usually documented on its manpage.
test and “[”
The shell’s test command
evaluates simple Boolean expressions involving numbers and strings,
setting its exit status to 0 (true) or 1 (false):
➜test 10 -lt 5Is 10 less than 5? ➜echo $?1 No, it isn’t ➜test -n "hello"Does the string “hello” have nonzero length? ➜echo $?0 Yes, it does
Here are common test
arguments for checking properties of integers, strings, and
files:
File tests | |
| File
|
| File
|
| File
|
| File
|
| File
|
| File ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access