O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

-d name

File name is a directory

-f name

File name is a regular file

-L name

File name is a symbolic link

-r name

File name exists and is readable

-w name

File name exists and is writable

-x name

File name exists and is executable

-s name

File name exists and its ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required