Booleans and Return Codes
Before we can describe conditionals and loops, we need to explain the concept of a Boolean (true/false) test. 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.)
Additionally, every Linux 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 myfile My name is Sandy Smith and I really like Ubuntu Linux $ grep Smith myfile My 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 test command (built
into the shell) will evaluate simple Boolean expressions involving
numbers and strings, setting its exit status to 0 (true) or 1
(false):
$ test 10 -lt 5 Is 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
|
|
|
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