Introduction to Shell Scripting with Bash
Operating System Shell Scripting
Introduction to Shells
Linux offers a variety of shells, including:
- Bourne shell (sh)
- C shell (csh)
- Korn shell (ksh)
- TC shell (tcsh)
- Bourne Again shell (bash)
Among these, bash is the most popular and widely used shell. It is sh-compatible and incorporates features from both the Korn shell (ksh) and C shell (csh). Bash adheres to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard and provides functional improvements over sh for both programming and interactive use.
Benefits of Shell Scripting
Shell scripting leverages the capabilities of the shell to automate tasks that would otherwise require manual execution of multiple commands. While programming languages are generally more powerful and faster, scripting languages like bash offer advantages in terms of portability and ease of use.
Programming languages typically involve compiling source code into an executable, whereas scripting languages are interpreted directly from the source code. Although interpreted programs are generally slower than compiled programs, the key benefit of scripting languages is their portability across different operating systems.
Text Editors for Scripting
Two major text editors commonly used in Linux for scripting are:
- vi
- emacs (or xemacs)
Example: Creating and Deleting a Directory
The following commands demonstrate how to create a directory, copy files into it, and then delete the directory along with its contents:
$ mkdir trash
$ cp * trash
$ rm -rf trash
$ mkdir trash
Variables in Bash
In bash scripting, there is no need to declare variables explicitly. Assigning a value to a variable name automatically creates it. The shell programming language does not perform type-casting on variables.
The backslash (\) character serves as the escape character in bash, preserving the literal value of the next character. When using double quotes to enclose a string, variables within the quotes are resolved, while single quotes prevent variable resolution.
The export command promotes a variable to the environment, making it accessible to child processes. However, if the child process modifies the variable, it does not affect the parent process’s original value.
Types of Variables
There are two main types of variables in bash:
- Local variables: These variables are only accessible within the current shell or script.
- Environmental variables: These variables are set by the system and can be viewed using the
envcommand. They hold special values and are defined in files such as /etc/profile, /etc/profile.d/, and ~/.bash_profile, which are considered initialization files.
When a login shell exits, bash reads the ~/.bash_logout file.
Common Environmental Variables
- HOME: The default directory for the
cdcommand (home directory). - PATH: A colon-separated list of directories searched when executing commands. Setting
PATH=$PATH:.includes the current working directory in the search path. - LOGNAME: Contains the username.
- HOSTNAME: Contains the computer name.
- RANDOM: Generates a random number.
- SECONDS: Tracks the number of seconds since the start of script execution.
Input and Output
The read command allows you to prompt for user input and store it in a variable.
Mathematical Operations
The let statement enables you to perform mathematical calculations. Arithmetic expressions can also be evaluated using $[expression] or $((expression)).
Conditionals
Conditionals allow you to control the flow of execution based on certain conditions. The if statement is commonly used for this purpose.
Positional Parameters
Positional parameters are assigned from the arguments passed to the shell script when it is invoked. Parameter “N” can be referenced as “${N}” or “$N” (for single-digit N).
Example: Trash Script
#!/bin/bash
if [ $# -eq 1 ]; then
if [ ! -d "$HOME/trash" ]; then
mkdir "$HOME/trash"
fi
mv $1 "$HOME/trash"
else
echo "Use: $0 filename"
exit 1
fi
Case Statement
The case statement provides a way to execute different blocks of code based on the value of a variable.
Debugging
Bash offers debugging options to help identify and resolve issues in scripts:
- -x: Displays each line of the script with variable substitution before execution.
- -v: Displays each line of the script as typed before execution.
Loops
While Loop
The while loop repeatedly executes a set of commands as long as a specified condition remains true.
Continue Statement
The continue command skips the remaining commands in the current loop iteration and jumps to the next iteration.
Break Statement
The break command terminates the loop immediately.
Until Loop
The until loop continues executing until a specified condition becomes true.
Functions
Functions enhance script maintainability and modularity by breaking down the code into smaller, reusable units. A function can perform a specific task and optionally return a value.
