Book Image

Linux Shell Scripting Cookbook

By : Sarath Lakshman
Book Image

Linux Shell Scripting Cookbook

By: Sarath Lakshman

Overview of this book

<p>GNU/Linux is a remarkable operating system that comes with a complete development environment that is stable, reliable, and extremely powerful. The shell being the native interface to communicate with the operating system is capable of controlling the entire operating system. There are numerous commands on Linux shell which are documented but hard to understand. The man pages are helpful but they are very lengthy and it does not give any clues on key areas where commands can be used. Proper usage of shell commands can easily solve many complex tasks with a few lines of code, but most linux users don't have the right know-how to use the Linux shell to its full potential.<br /><br />Linux Shell Scripting Cookbook is a collection of essential command-line recipes along with detailed descriptions tuned with practical applications. It covers most of the commands on Linux with a variety of usecases accompanied by plenty of examples. This book helps you to perform complex data manipulations involving tasks such as text processing, file management, backups and more with the combination of few commands.<br /><br />Linux Shell Scripting Cookbook shows you how to capitalize on all the aspects of Linux using the shell scripting language. This book teaches you how to use commands to perform simple tasks all the way to scripting complex tasks such as managing large amounts of data on a network.</p> <p>It guides you on implementing some of the most common commands in Linux with recipes that handle any of the operations or properties related with files like searching and mining inside a file with grep. It also shows you how utilities such as sed, awk, grep, cut can be combined to solve text processing related problems. The focus is on saving time by automating many activities that we perform interactively through as browser with a few lines of script.</p> <p>This book will take you from a clear problem description to a fully functional program. The recipes contained within the chapter will introduce the reader to specific problems and provide hands-on solutions.</p>
Table of Contents (16 chapters)
Linux Shell Scripting Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Functions and arguments


Like any other scripting languages, Bash also supports functions. Let's see how to define and use functions.

How to do it...

A function can be defined as follows:

function fname()
{
statements;
}

Or alternately,

fname()
{
statements;
}

A function can be invoked just by using its name:

$ fname ; # executes function

Arguments can be passed to functions and can be accessed by our script:

fname arg1 arg2 ; # passing args

Following is the definition of the function fname. In the fname function, we have included various ways of accessing the function arguments.

fname()
{
  echo $1, $2; #Accessing arg1 and arg2
  echo "$@"; # Printing all arguments as list at once
  echo "$*"; # Similar to $@, but arguments taken as single entity
  return 0; # Return value
}

Similarly, arguments can be passed to scripts and can be accessed by script:$0 (the name of the script):

  • $1 is the first argument

  • $2 is the second argument

  • $n is the nth argument

  • "$@" expands as "$1" "$2" "$3" and so on

  • "$*" expands as "$1c$2c$3", where c is the first character of IFS

  • "$@" is the most used one. "$*" is used rarely since it gives all arguments as a single string.

There's more...

Let's explore more tips on Bash functions.

Recursive function

Functions in Bash also support recursion (the function that can call itself). For example, F() { echo $1; F hello; sleep 1; }.

Tip

Fork bomb

:(){ :|:& };:

This recursive function is a function that calls itself. It infinitely spawns processes and ends up in a denial of service attack. & is postfixed with the function call to bring the subprocess into the background. This is a dangerous code as it forks processes and, therefore, it is called a fork bomb.

You may find it difficult to interpret the above code. See Wikipedia page http://en.wikipedia.org/wiki/Fork_bomb for more details and interpretation of the fork bomb.

It can be prevented by restricting the maximum number of processes that can be spawned from the config file /etc/security/limits.conf.

Exporting functions

A function can be exported like environment variables using export such that the scope of the function can be extended to subprocesses, as follows:

export -f fname

Reading command return value (status)

We can get the return value of a command or function as follows:

cmd; 
echo $?;

$? will give the return value of the command cmd.

The return value is called exit status. It can be used to analyze whether a command completed its execution successfully or unsuccessfully. If the command exits successfully, the exit status will be zero, else it will be non-zero.

We can check whether a command terminated successfully or not as follows:

#!/bin/bash
#Filename: success_test.sh
CMD="command" #Substitute with command for which you need to test exit status
$CMD
if [ $? –eq 0 ];
then
echo "$CMD executed successfully"
else
echo "$CMD terminated unsuccessfully"
fi

Passing arguments to commands

Arguments to commands can be passed in different formats. Suppose –p and -v are the options available and -k NO is another option that takes a number. Also the command takes a filename as argument. It can be executed in multiple ways as follows:

$ command -p -v -k 1 file

Or:

$ command -pv -k 1 file

Or:

$ command -vpk 1 file

Or:

$ command file -pvk 1