[Bash] Use Conditional Statements in Bash
in use Bash Conditional statements
2023-09-14 08:59:13 时间
Knowing how conditionals work in bash open up a world of scripting possibilities. We’ll learn the basic syntax, including if, else, and elif. Then we'll look at a few of the "primary" operators you can leverage in a conditional statement such as = for string equality, -eq for numeric equality, and -e to check if a file exists. After that, we'll use conditional statements to create a function that asserts that the HTTP status of a given URL is between 200 and 299.
Basic conditional block:
```bash
if [[ ]]; then
fi
Exp:
if [[ $USER = 'username' ]]; then
echo "true"
else
echo "false"
fi
not equal: !=
numeric equality: -eq
not equals: -ne
is empty: -z
if [[ 1 -eq 1 ]];
if [[ -z $USER ]];
Elif
if [[ -z $USER ]]; then
echo "user is empty"
elif [[ 1 -eq 1 ]]; then
echo "1==1"
else
echo "false"
fi
Ternary
[[ $USER = 'username' ]] && echo "yes" || echo "no"
Exp:
check_status() {
## Get HTTP status code
local status=$(curl -ILs $1 | head -n 1 | cut -d ' ' -f 2)
if [[ $status -lt 200 ]] || [[ $status -gt 299 ]]; then
echo "$1 failed with a $status"
return 1
else
echo "$1 succeeded with a $status"
fi
}
check_status https://example.com
check_status https://example.com/404
相关文章
- H-Fashion in Berland
- 【错误记录】Android Studio 编译报错 ( To use data binding annotations in Kotlin, apply the ‘kotlin-kapt‘ plu )
- ORA-23418: cannot unregister the propagator who is currently in use ORACLE 报错 故障修复 远程处理
- ORA-30014: operation only supported in Automatic Undo Management mode ORACLE 报错 故障修复 远程处理
- ORA-30679: JDWP-based debugging not supported in this configuration ORACLE 报错 故障修复 远程处理
- ORA-32037: unsupported use of LEVEL in membership condition ORACLE 报错 故障修复 远程处理
- ORA-38862: Flashback database logs are in use. ORACLE 报错 故障修复 远程处理
- ORA-48343: invalid field [string] reference in string clause ORACLE 报错 故障修复 远程处理
- ORA-01234: cannot end backup of file string – file is in use or recovery ORACLE 报错 故障修复 远程处理
- ORA-02020: too many database links in use ORACLE 报错 故障修复 远程处理
- ORA-16223: DDL skipped, unsupported in current version ORACLE 报错 故障修复 远程处理
- no main manifest attribute, in demo-1.0.jar详解编程语言
- 查询Oracle中执行多列IN查询的技巧(oracle多列in)
- Exploring the Power of Signals in Linux C Programming(linuxc信号)
- 用法Oracle IN 用法简介(oracle的in)
- MySQL使用IN查询时数量超限问题的解决方法(mysql中in超过数量)
- MySQL中使用IN操作符的查询效率分析(mysql中in的效率)
- MySQL中in和等于操作的使用技巧(mysql中in和等于)
- 无需使用USE命令,轻松管理MySQL数据库(mysql不用use)
- 优化MySQL查询避免使用IN关键字(mysql 不用 in)
- 语法 在Oracle中使用IN子句实现查询(oracle中支持in)