shell变量的定义与赋值
- 为区分字符串常量和变量引用,Shell要求通过美元符号($)来引用变量
- 不必事先定义变量,在该变量赋值时会自动获得定义,未经定义的Shell变量也可以引用,只是变量值为空
- 若被引用的Shell变量名后紧接着字母、数字下划线等字符,应该将变量用花括号({})括起来
- 为区分赋值表达式中的Linux命令和字符串常量,Linux命令需要用反引号(``)括起来
#!/bin/bash
num=3
guest1=Alice
guest2="Bill Gates" #因为字符串中间存在空格,需要用双引用
msg="$guest1 logs out before the ${num}th day" #$引用变量,变量名后紧接着字符串th,需要加花括号
echo $msg
echo "current directory of ${guest2} is `pwd`." #pwd是Linux命令需要用反引号
输入输出
输入
read [-s] [-p prompt] var1 var2
# -s:默读,就像输入密码,不会显示输入的内容
# -p prompt:在用户输入前显示提示字符串prompt
输出
echo message
数学运算
方式一:expr 表达式
方式二:$[expression]
字符串处理
shell对字符串处理主要是通过exp、awk等命令实现
- 抽取字符串
# expr substr 字符串 开始索引 长度
str=`expr substr "abc" 2 2` # bc
# ${str:pos}
# ${str:pos:len}
str="abc"
str2={str:1} # bc
str3={str:1:2} # bc
- 计算字符串长度
# ${#string}
# expr length $string
str=abcedf
n1=${#str} # 5
n2=`expr length $str` # 5
- 计算字符串的出现位置
# expr index #string substring
str="hello,everyone"
n1=`expr index "$str" my` # 0
n2=`expr index "$str" ev` # 2
n3=`expr index "$str" ev.*` # 2
- 返回匹配到的字符串的长度
# expr match $string substring
string="hello,everyone"
n1=`expr match "$string" he` # 2
n2=`expr match "$string" he.*` #14
- 删除字符串
# ${string#substring} 删除string开头处与substring匹配的最短字符串
# ${string##substring} 删除string开头处与substring匹配的最长字符串
str="20091111 readnow please"
str1=${str#2*1} # 结果为111 readnow please(删除从2开始到第一个1为止的子串)
str2=${str##2*1} #结果为 readnow please(删除从2开始到最后一个1为止的子串)
逻辑语句
条件语句if
#!/bin/bash
if date #date命令的终止代码为if的判断条件
then
echo "ite worked"
elif command
echo "..."
fi
linux 提供了test指令来实现条件检测功能,test condition 计算出是true或者是false。在if-then语句用生命test命令有一种更简便的方法–使用中括号(!!!第一个括号的后面和第二个后面的前面必须有一个空格)
if [ condition ]
then
commands
复合条件检查可以使用逻辑操作符
… [ condition1 ] && [ condition2 ]
… [ condition1 ] || [ condition2 ]
数值比较
数学表达式 | shell语法 |
---|---|
n1=n2 | n1 -eq n2 |
n1<=n2 | n1 -le n2 |
n1>=n2 | n1 -ge n2 |
n1<n2 | n1 -lt n2 |
n1>n2 | n1 -gt n2 |
n1!=n2 | n1 -ne n2 |
字符串比较
shell语句 | 含义 |
---|---|
str1=str2 | 检查字符串是否相同 |
str1<str2 | 检查str1是否小于str2 |
str1>str2 | 检查str1是否大于str2 |
str1!=str2 | 检查str1与str2是否不同 |
-n str1 | 检查str1的长度是否大于0 |
-z str1 | 检查str1的长度是否为0 |
文件比较
比较 | 描述 |
---|---|
-d file | 检查是否存在并且是同一个目录 |
-e file | 检查是否存在 |
-f file | 检查是否存在并且是一个文件 |
-r file | 检查是否存在并且可读 |
-w file | 检查是否存在并且可写 |
-x file | 检查是否存在并且可执行 |
-O file | 检查是否存在并且被当前用户拥有 |
-G file | 检查是否存在并且默认值为当前用户组 |
file1 -nt file2 | 检查file1是否比file2新 |
file1 -oz file2 | 检查file1是否比file2旧 |
case语句
用 | 将每个模式分开,* 号表示任何列出的模式都不匹配的所有值。每个条件后使用 ) ,每个表达式后使用两个分号。
case varibale in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
循环结构for
for var in list
do
commands
done
循环结构while
while test command
do
other commands
done
循环结构until
until刚好与while命令相反,当测试命令产生非0的终止状态时,循环就继续,直到测试命令的终止状态码0。
until test commands
do
other commands
done