Using the if keyword

A shell script is fundamentally a sequence of commands. In such a script, we very often want to run a command only if a testable condition is true. In earlier chapters, we already saw one way to do this, with the && control operator:

$ grep -q bash /etc/shells && printf 'Bash is a system shell\n'

The preceding command line separates two commands with &&. The second command, which prints a string to standard output, only runs if the first command, grep -q bash /etc/shells, finds the bash string in the /etc/shells file and hence exits with status zero (success).

Using the if keyword, we can make this conditional approach more flexible, and somewhat easier to read:

$ if grep -q bash /etc/shells ; then printf 'Bash is a system ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.