螺竹编程
发布于 2024-08-04 / 2 阅读
0

Shell/Bash:Bash运算与运算符

在Bash中,可以使用运算符进行数值运算和比较。下面是一些常用的运算符及其示例:

算术运算符

算术运算符主要用于执行基本的算术运算,如加减乘除和取模。下面是一些常用的算术运算符及其示例:

+  # 加
echo $((2 + 3))  # 输出:5

-  # 减
echo $((5 - 3))  # 输出:2

*  # 乘
echo $((3 * 4))  # 输出:12

/  # 除
echo $((10 / 3))  # 输出:3

%  # 取模
echo $((10 % 3))  # 输出:1

比较运算符

比较运算符主要用于比较两个数值的大小。下面是一些常用的比较运算符及其示例:

-eq  # 等于
if [ 2 -eq 2 ]; then echo "2 equals 2"; fi  # 输出:2 equals 2

-ne  # 不等于
if [ 2 -ne 3 ]; then echo "2 does not equal 3"; fi  # 输出:2 does not equal 3

-gt  # 大于
if [ 3 -gt 2 ]; then echo "3 is greater than 2"; fi  # 输出:3 is greater than 2

-lt  # 小于
if [ 2 -lt 3 ]; then echo "2 is less than 3"; fi  # 输出:2 is less than 3

-ge  # 大于等于
if [ 3 -ge 3 ]; then echo "3 is greater than or equal to 3"; fi  # 输出:3 is greater than or equal to 3

-le  # 小于等于
if [ 2 -le 3 ]; then echo "2 is less than or equal to 3"; fi  # 输出:2 is less than or equal to 3

逻辑运算符

逻辑运算符主要用于组合条件语句。下面是一些常用的逻辑运算符及其示例:

!   # 非
if ! [ 2 -eq 3 ]; then echo "2 does not equal 3"; fi  # 输出:2 does not equal 3

-a  # 与(and)
if [ 2 -eq 2 -a 3 -eq 3 ]; then echo "2 equals 2 and 3 equals 3"; fi  # 输出:2 equals 2 and 3 equals 3

-o  # 或(or)
if [ 2 -eq 2 -o 3 -eq 4 ]; then echo "2 equals 2 or 3 equals 4"; fi  # 输出:2 equals 2 or 3 equals 4

字符串运算符

字符串运算符主要用于比较字符串的内容。下面是一些常用的字符串运算符及其示例:

=   # 等于
if [ "hello" = "hello" ]; then echo "hello equals hello"; fi  # 输出:hello equals hello

!=  # 不等于
if [ "hello" != "world" ]; then echo "hello does not equal world"; fi  # 输出:hello does not equal world

-z  # 长度为零
if [ -z "" ]; then echo "the string is empty"; fi  # 输出:the string is empty

-n  # 长度不为零
if [ -n "hello" ]; then echo "the string is not empty"; fi  # 输出:the string is not empty

文件测试运算符

文件测试运算符主要用于测试文件的状态。下面是一些常用的文件测试运算符及其示例:

-e  # 文件存在
if [ -e /etc/passwd ]; then echo "the file exists"; fi  # 输出:the file exists

-d  # 文件是目录
if [ -d /etc ]; then echo "the directory exists"; fi  # 输出:the directory exists

-f  # 文件是普通文件
if [ -f /etc/passwd ]; then echo "the file is a regular file"; fi# 输出:the file is a regular file

-r  # 文件可读
if [ -r /etc/passwd ]; then echo "the file is readable"; fi  # 输出:the file is readable

-w  # 文件可写
if [ -w /etc/passwd ]; then echo "the file is writable"; fi  # 输出:the file is writable

-x  # 文件可执行
if [ -x /bin/bash ]; then echo "the file is executable"; fi  # 输出:the file is executable