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

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.
主站蜘蛛池模板: 临武县| 新郑市| 延川县| 视频| 米林县| 福安市| 六枝特区| 达日县| 忻州市| 崇文区| 泸水县| 西峡县| 鄢陵县| 靖宇县| 高陵县| 玉屏| 阳东县| 冀州市| 南岸区| 石家庄市| 什邡市| 盘山县| 林州市| 丹凤县| 乌拉特后旗| 库车县| 灵丘县| 罗源县| 惠州市| 资源县| 九龙坡区| 搜索| 新竹县| 合水县| 宜兰县| 克拉玛依市| 云梦县| 独山县| 略阳县| 平泉县| 元氏县|