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

  • 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.

主站蜘蛛池模板: 图木舒克市| 沾化县| 上饶县| 出国| 吴桥县| 达日县| 阳信县| 五峰| 通海县| 开江县| 普兰店市| 乌兰浩特市| 同德县| 大竹县| 齐齐哈尔市| 海门市| 古交市| 庆阳市| 大余县| 黔西| 社旗县| 哈尔滨市| 西昌市| 晋城| 随州市| 嘉义市| 鲁山县| 万宁市| 武功县| 长治县| 漯河市| 江孜县| 石泉县| 通辽市| 买车| 藁城市| 大庆市| 肇源县| 秦皇岛市| 邵阳县| 邵东县|