A working knowledge of shell scripting is vital if someone wants to become good at system administration tasks. Since this tutorial tackles topics that assume a basic understanding of shell scripting, we strongly urge you to take a look at our Shell Scripting: The Basics article first…
One important aspect of shell scripting is file-oriented utility. A file-oriented utility is basically used as a filter in a pipe.
We can add a ‘-’ to get a more useful result. That is, when we have ‘file -’, the shell waits for the user input and analyses it.
So if we pass #!/bin/bash as an input, then we can expect the following as an output:
[sourcecode language=”bash”]standard input: Bourne-Again shell script text executable
In the last article, we had a look at the variables and learnt that a variable is a placeholder for its value. The name of a variable is called an lvalue (as it appears on the left side of an assignment statement) and a variable’s value is its rvalue. A variable’s name is also a pointer to the memory location where we have the actual data associated with that variable. Out of all types of variables, one needs to focus on environmental variables as these are the variables that affect the behaviour of the shell and user interface.
One can pass command-line arguments to a shell script. When we pass arguments, $0 will be the name of the script itself, $1 is the first argument, $2 is the second argument and so on. We need to note here that from the command line, $0 is the name of the shell.
Just as in C programs, an exit command terminates a script. It can also return a value and this value can be made available to the script’s parent process. We know that on successful execution a command returns an integer value of 0, while a non-zero value will be returned in case of any errors. It is important to note here that when a script ends with an exit that has no parameter, the exit status of the script is the exit status of the last command executed in the script. $? reads the exit status of the last command executed. Thus when a function returns, we can get the exit status of the last command executed in the function by echoing the value of $?. One can get the exit status of the script from the command line by using this $?. And it will be 0 if the script has executed successfully.
In our last article on shell scripting, we had a brief look at some of the control constructs and they basically help us in testing for a condition. A large number of file test operators are available and using these operators, one can check…
a. If a file exists or not.
b. If the file size is zero or not.
c. If the file is a regular file or a block device or a character device.
d. If the file has read permission or write permission.
We also have operators that perform various operations on strings. Let us look at a sample script to understand one such aspect.
if [ -z “$string” ]
echo “We have a null string”
echo “String is not null”
Continue to page 2…