- Bash Cookbook
- Ron Brash Ganesh Naik
- 282字
- 2021-07-23 19:17:29
Conditional logic using if, else, and elseif
The previous section introduced the concept that there are several reserved words and a number of characters that have an effect on the operation of Bash. The most basic, and probably most widely used conditional logic is with if and else statements. Let's use an example code snippet:
#!/bin/bash
AGE=17
if [ ${AGE} -lt 18 ]; then
echo "You must be 18 or older to see this movie"
fi
If we are evaluating the variable age using less than (<) or -lt (Bash offers a number of syntactical constructs for evaluating variables), we need to use an if statement. In our if statement, if $AGE is less than 18, we echo the message You must be 18 or older to see this movie. Otherwise, the script will not execute the echo statement and will continue execution. Notice that the if statement ends with the reserved word fi. This is not a mistake and is required by Bash syntax.
Let's say we want to add a catchall using else. If the then command block of the if statement is not satisfied, then the else will be executed:
#!/bin/bash
AGE=40
if [ ${AGE} -lt 18 ]
then
echo "You must be 18 or older to see this movie"
else
echo "You may see the movie!"
exit 1
fi
With AGE set to the integer value 40, the then command block inside the if statement will not be satisfied and the else command block will be executed.
- The Supervised Learning Workshop
- 軟件架構(gòu)設(shè)計(jì):大型網(wǎng)站技術(shù)架構(gòu)與業(yè)務(wù)架構(gòu)融合之道
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- Android 9 Development Cookbook(Third Edition)
- Microsoft System Center Orchestrator 2012 R2 Essentials
- PHP+MySQL網(wǎng)站開(kāi)發(fā)項(xiàng)目式教程
- Mastering Linux Network Administration
- jQuery炫酷應(yīng)用實(shí)例集錦
- Advanced Express Web Application Development
- ASP.NET程序開(kāi)發(fā)范例寶典
- Building Serverless Web Applications
- JavaScript+jQuery網(wǎng)頁(yè)特效設(shè)計(jì)任務(wù)驅(qū)動(dòng)教程
- Responsive Web Design with jQuery
- Python數(shù)據(jù)可視化之matplotlib實(shí)踐
- Appcelerator Titanium Smartphone App Development Cookbook