- Bash Cookbook
- Ron Brash Ganesh Naik
- 308字
- 2021-07-23 19:17:29
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:
- If MY_NAME is equal to Ron, then echo "Ron is home from vacation"
- 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"
- 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"
- 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.
推薦閱讀
- Mastering Adobe Captivate 2017(Fourth Edition)
- Java系統(tǒng)分析與架構(gòu)設(shè)計
- Practical UX Design
- PostgreSQL Cookbook
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優(yōu)化計算
- Java Web基礎(chǔ)與實例教程
- Interactive Applications Using Matplotlib
- Mastering Rust
- RISC-V體系結(jié)構(gòu)編程與實踐(第2版)
- Python機器學(xué)習(xí)算法: 原理、實現(xiàn)與案例
- 從零開始學(xué)C#
- 軟件體系結(jié)構(gòu)
- Python網(wǎng)絡(luò)爬蟲技術(shù)與應(yīng)用
- C陷阱與缺陷
- 零基礎(chǔ)學(xué)HTML+CSS