a=z # Assign the string "z" to variable a.
b="a string" # Embedded spaces must be within quotes.
c="a string and $b" # Other expansions such as variables can be
# expanded into the assignment.
d=$(ls -l foo.txt) # Results of a command.
e=$((5 * 7)) # Arithmetic expansion.
f="\t\ta string\n" # Escape sequences such as tabs and newlines.
ls -d /usr/bin && echo $? => 0 # 检测存在的目录,退出状态为0.代表成功。
ls -d /bin/usr && echo $? => 2 # 检测不存在的目录,退出状态为2.代表失败。
判断表达式:[ expression ]
常用检测文件表达式:
常用检测字符串表达式:
常用检测整型表达式:
现代判断表达式:[[ expression ]]
支持原test表达式,新增支持 string =~ regex 支持匹配正则判断。 新增支持==操作符支持类型匹配
#! /bin/bash
# 检测一个值是不是数字
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
echo "this is a number!"
fi
现代整型判断表达式:(( expression ))
#! /bin/bash
INT=-5
if ((INT == -5)); then
echo "this is -5"
fi
结合表达式:
操作符 测试表达式[] 现代表达式[[]] (())
AND -a &&
OR -o ||
NOT ! !