📅  最后修改于: 2023-12-03 15:13:38.093000             🧑  作者: Mango
Bash是一种Unix Shell,它提供了一种命令行界面和脚本语言,它是许多Linux发行版的默认shell。Bash支持许多不同的表达式,本文将介绍一些最常用的bash表达式。
Bash支持整型和浮点数的算术运算,使用如下表达式:
# 整型加法
num1=10
num2=20
result=$((num1+num2))
echo $result # 30
# 整型减法
num3=5
result=$((num1-num3))
echo $result # 5
# 整型乘法
result=$((num1*num3))
echo $result # 50
# 整型除法
result=$((num2/num3))
echo $result # 4
# 浮点数运算
num4=1.5
num5=2.5
result=$(echo "$num4 + $num5" | bc)
echo $result # 4.0
Bash还支持字符串操作,如下表达式:
# 字符串拼接
str1="Hello"
str2="World"
result="$str1 $str2"
echo $result # Hello World
# 比较字符串是否相等
if [ "$str1" = "Hello" ]
then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
# 比较字符串是否不相等
if [ "$str1" != "$str2" ]
then
echo "Strings are not equal"
else
echo "Strings are equal"
fi
# 获取字符串长度
str3="Hello world"
len=${#str3}
echo $len # 11
# 截取子字符串
sub_str=${str3:0:5}
echo $sub_str # Hello
在Bash中,可以使用以下表达式进行逻辑运算:
# 逻辑或
if [ "$num1" -eq 10 ] || [ "$num2" -eq 30 ]
then
echo "At least one condition is true"
else
echo "Both conditions are false"
fi
# 逻辑与
if [ "$num1" -eq 10 ] && [ "$num2" -eq 20 ]
then
echo "Both conditions are true"
else
echo "At least one condition is false"
fi
# 布尔非
if ! [ "$num1" -eq 20 ]
then
echo "num1 is not equal to 20"
else
echo "num1 is equal to 20"
fi
Bash可以使用文件表达式来检查文件的属性,如下面的示例所示:
# 检查文件是否存在
if [ -e "file.txt" ]
then
echo "File exists"
else
echo "File does not exist"
fi
# 检查文件是否可读
if [ -r "file.txt" ]
then
echo "File is readable"
else
echo "File is not readable"
fi
# 检查文件是否可写
if [ -w "file.txt" ]
then
echo "File is writable"
else
echo "File is not writable"
fi
# 检查文件是否可执行
if [ -x "file.sh" ]
then
echo "File is executable"
else
echo "File is not executable"
fi
以上是Bash中最常用的表达式之一,可以帮助您更好地编写Shell脚本。