- 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.
推薦閱讀
- Java語言程序設計
- Monkey Game Development:Beginner's Guide
- Oracle Database In-Memory(架構與實踐)
- Learning Linux Binary Analysis
- Learn Programming in Python with Cody Jackson
- Internet of Things with Intel Galileo
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Flux Architecture
- C++ 從入門到項目實踐(超值版)
- jQuery炫酷應用實例集錦
- Programming with CodeIgniterMVC
- CodeIgniter Web Application Blueprints
- 寫給青少年的人工智能(Python版·微課視頻版)
- JavaScript Concurrency
- 編程的原則:改善代碼質量的101個方法