Book Image

Mastering Linux Shell Scripting

By : Andrew Mallett
Book Image

Mastering Linux Shell Scripting

By: Andrew Mallett

Overview of this book

Shell scripting is a quick method to prototype a complex application or a problem by automating tasks when working on Linux-based systems. Using both simple one-line commands and command sequences complex problems can be solved with ease, from text processing to backing up sysadmin tools. In this book, you’ll discover everything you need to know to master shell scripting and make informed choices about the elements you employ. Get to grips with the fundamentals of creating and running a script in normal mode, and in debug mode. Learn about various conditional statements' code snippets, and realize the power of repetition and loops in your shell script. Implement functions and edit files using the Stream Editor, script in Perl, program in Python – as well as complete coverage of other scripting languages to ensure you can choose the best tool for your project.
Table of Contents (21 chapters)
Mastering Linux Shell Scripting
About the Author
About the Reviewer

Recapping test

So far we have used the built-in test command to drive our conditional statements. Using other options with test, we can look at the returned value to determine the status of files in the file system. Running the test without any option will return a false output:

$ test

Testing files

Commonly, we can use test to check the conditions based around files. For example, to test that a file is present, or not, we can use the-e option. The following command will test the existence of the /etc/hosts file:

test -e /etc/hosts

We can run this test again, but this time check that the file not only exists but is a regular file as opposed to having some special purpose. Specific file types can be directories, pipes, links, and so on. The option for a regular file is -f.

$ test -f /etc/hosts

Adding logic

If we need to open a file from within our script, we will test that the file is both a regular file and has the read permission set. To achieve this with test, we can also include the -a option...