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

Evaluating strings

As mentioned in the variables subsection, numeric values are different from strings. Strings are typically evaluated like this:

#!/bin/bash
MY_NAME="John"
NAME_1="Bob"
NAME_2="Jane"
NAME_3="Sue"
Name_4="Kate"

if [ "${MY_NAME}" == "Ron" ]; then
echo "Ron is home from vacation"
elif [ "${MY_NAME}" != ${NAME_1}" && "${MY_NAME}" != ${NAME_2}" && "${MY_NAME}" == "John" ]; then
echo "John is home after some unnecessary AND logic"
elif [ "${MY_NAME}" == ${NAME_3}" || "${MY_NAME}" == ${NAME_4}" ]; then
echo "Looks like one of the ladies are home"
else
echo "Who is this stranger?"
fi

In the preceding snippet, you might notice that the MY_NAME variable will be executed and the string John is home after some unnecessary AND logic will be echoed to the console. In the snippet, the logic flows like this:

  1. If MY_NAME is equal to Ron, then echo "Ron is home from vacation"
  2. Else if MY_NAME is not equal to NAME_1 AND MY_NAME is not equal to NAME_2 AND MY_NAME is equal to John, then echo "John is home after some unnecessary AND logic"
  3. Else if MY_NAME is equal to NAME_3 OR MY_NAME is equal to NAME_4, then echo "Looks like one of the ladies"
  4. Else echo "Who is this stranger?"

Notice the operators: &&, ||, ==, and != 

  • && (means and)
  • || (means or)
  • == (is equal to)
  • != (not equal to)
  • -n (is not null or is not set)
  • -z (is null and zero length)
Null means not set or empty in the world of computing. There are many different types of operators or tests that can be used in your scripts. For more information, check out:  http://tldp.org/LDP/abs/html/comparison-ops.html and  https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic
You can also evaluate numbers as if they are strings using (("$a" > "$b")) or [[ "$a" > "$b" ]]. Notice the usage of double parentheses and square brackets.
主站蜘蛛池模板: 祥云县| 甘肃省| 高尔夫| 福海县| 普兰店市| 台前县| 桃江县| 德格县| 景德镇市| 麻城市| 麻城市| 长葛市| 庆云县| 西华县| 安阳县| 抚远县| 二手房| 墨竹工卡县| 商洛市| 苍山县| 时尚| 巴青县| 灵山县| 合川市| 溧阳市| 道真| 东乡族自治县| 罗城| 中江县| 怀仁县| 紫金县| 特克斯县| 封开县| 和林格尔县| 武威市| 舞钢市| 栾城县| 滨州市| 淮北市| 蒙城县| 北碚区|