Bash
命令
set 命令
set -o pipefail :在 Bash 中,管道(|)默认仅以最后一个命令的退出状态作为整个管道的返回值,开启这个选项后,管道中任意一个命令失败都会导致整个管道返回非 0 状态码。
set -e :任意命令出错都会导致退出
并行执行
for arg in "aa bb"
./program & # 在子进程中执行
fi
wait # 等待所有子进程执行完
条件判断
[ 与[[
[是 test 命令[[是 Bash 的扩展测试命令,提供了更强大的功能
逻辑运算符
在 Bash 中,运算符的优先级如下:
逻辑运算符:
!(逻辑非)&&(逻辑与)||(逻辑或)
比较运算符:
eq,ne,lt,le,gt,ge(数字比较)=,!=,<,>(字符串比较)
可以使用括号指定优先级
if [[ "$a" -lt "$b" && "$b" -gt 15 ]]; then
echo "Both conditions are true: a is less than b and b is greater than 15."
fi
if [[ ("$a" -lt "$b") && ("$b" -gt 15) ]]; then
echo "Both conditions are true."
fi
字符串匹配
== 用于相等关系的判断
if [[ "$string" == _substring_ ]]; then
echo "Contains substring"
fi
=~ 则用于正则关系匹配
if [[ "$string" =~ pattern ]]; then
echo "Matches regex"
fi
其中 pattern 是用正则表达式的语法的模式串
比较
相等
if [[ "$str1" == "$str2" ]]; then
echo "Strings are equal"
fi
if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
fi
字典序大小比较
if [[ "$str1" < "$str2" ]]; then
echo "$str1 comes before $str2"
fi
if [[ "$str1" > "$str2" ]]; then
echo "$str1 comes after $str2"
fi
不等
if [[ "$str1" != "$str2" ]]; then
echo "Strings are not equal"
fi
空非空字符串检查
if [[ -z "$str1" ]]; then
echo "String is empty"
fi
if [[ -n "$str1" ]]; then
echo "String is not empty"
fi
数字比较
if [ "$num1" -eq "$num2" ]; then
echo "Numbers are equal"
fi
if [ "$num1" -ne "$num2" ]; then
echo "Numbers are not equal"
fi
if [ "$num1" -gt "$num2" ]; then
echo "$num1 is greater than $num2"
fi
if [ "$num1" -lt "$num2" ]; then
echo "$num1 is less than $num2"
fi
if [ "$num1" -le "$num2" ]; then
echo "$num1 is less than or equal to $num2"
fi
注意事项
- 最好都加引号,防止解析出错
- 使用[时,必须在括号和条件之间添加空格。
- [[支持逻辑运算符&&和 ||, [则不支持
- [[ 允许使用模式匹配(如 == 和 !=),支持通配符 * 和 ?, [判断相等得用=
- 使用 [[ 时,如果变量未定义,返回空字符串不会导致错误。使用 [ 时,如果未定义变量,会导致错误