Mastering 'if else' in Shell Script: Practical Examples
In the realm of shell scripting, the if-else construct is a fundamental building block, enabling scripts to make decisions based on certain conditions. This article explores the usage of if-else in shell scripts, complete with examples to illustrate its functionality.
Before delving into the intricacies of if-else statements, let's briefly recap the basic syntax. The general structure is as follows:
```bash if condition then command1 command2 ... else command3 command4 ... fi ```Understanding the Basic If-Else Syntax
The if keyword is followed by a condition enclosed in square brackets. If the condition evaluates to true, the commands following the then keyword are executed. If the condition is false, the commands after the else keyword are executed. The fi keyword marks the end of the if-else statement.
Now, let's dive into some examples to solidify your understanding.
Example 1: Simple If-Else Statement
Here's a simple example that checks if a user-supplied number is positive, negative, or zero:
In this script, the user is prompted to enter a number. The if-else statement then checks the value and prints an appropriate message.
Example 2: If-Else with String Comparison
Shell scripts can also compare strings using the = operator. Here's an example:
```bash read -p "Enter your name: " name if [ "$name" = "John Doe" ] then echo "Hello, $name!" else echo "You are not John Doe." fi ```In this case, the script greets the user if their name is "John Doe"; otherwise, it informs them that they are not John Doe.
Nested If-Else Statements
Shell scripts can contain nested if-else statements, allowing for more complex decision-making processes. Here's an example that checks if a number is within a specific range:
```bash read -p "Enter a number: " num if [ $num -ge 0 ] then if [ $num -le 10 ] then echo "The number is between 0 and 10." else echo "The number is greater than 10." fi else echo "The number is negative." fi ```In this script, the outer if-else statement checks if the number is non-negative. If it is, the inner if-else statement checks if it's within the range of 0 to 10. If the number is negative, the script prints a message indicating that.
Mastering if-else statements in shell scripts empowers you to create dynamic and versatile scripts tailored to your specific needs. Practice and experimentation are key to unlocking the full potential of this essential shell scripting construct.
As you continue your shell scripting journey, remember to explore other control flow constructs, such as case statements and loops, to further expand your scripting capabilities. Happy coding!