官术网_书友最值得收藏!

  • 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
Notice the space after or before the square brackets in the if statement. Bash is particularly picky about the syntax of bracketing.

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.

主站蜘蛛池模板: 东乡族自治县| 景泰县| 独山县| 原平市| 板桥市| 甘孜县| 苏州市| 黄龙县| 东乌珠穆沁旗| 阿勒泰市| 渑池县| 莎车县| 普陀区| 肥乡县| 全椒县| 邵东县| 水城县| 台北市| 湘潭市| 石台县| 枞阳县| 南宫市| 罗城| 汽车| 辰溪县| 诏安县| 闽清县| 彭水| 建始县| 新邵县| 万全县| 临沧市| 永兴县| 二手房| 北流市| 奉贤区| 盐亭县| 尉氏县| 宝清县| 白山市| 丰宁|