1.创建shell脚本文件
首先必须在文件的第一行指定要使用的shell。
#!/bin/bash
2.条件判断
if-then 只能测试命令退出状态码的条件
# if-then结构 当command命令退出状态码为0(即成功运行时)执行then后面内容
if command;then
commands
fi
#if-then-else结构
if command; then
commands
else
commands
fi
#if-then-elif-then
I
if command1
then
commands
elif command2
then
commands
fi
test命令:提供了在if-then语句中测试不同条件的途径(如果数值比较等)
语法 test condition (如果条件成立,test命令就会退出并返回回0的退出状态码)
if test condition
then
commands
fi
复合条件判断:
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
注:bash shell下语法可以是 [ condition ] 注意条件首尾要加上空格
*****数值比较*****
n1 -eq n2 检查n1是否与n2相等
n1 -ge n2 检查n2是否大于或等于n2
-gt 检查n2是否大于n2
-le 小于或等于
-lt 小于
-ne 不等于
example:
value1=10
value2=11
if [ $value1 -gt 5 ]
then
echo "The test value $value1 is greater than 5"
fi
注:bash shell只能处理整数 test命令不能比较浮点数大小
*****字符串比较*****
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
-x
-s file 检查file是否存在并非空
*****高级特征*****
双括号 (( expression )) 使用高级数学表达式-----(( val++ ))
[[ expression ]] 字符串的模式匹配
case命令
语法:
case variable in
pattern1 | pattern2)
commands1
;;
pattern3)
commands
;;
*)
commands
;;
esac
3.循环
for命令
语法:
for var in list
do
commands
done
example1:读取值列表
list="Hadoop Hive Spark"
for test in $list
do
echo "I want to study $test"
done
注:向变量中储存的已有文本字符串尾部添加文本的一个常用方法:list=$list" Mapreduce"
while
语法:
while test command
do
other commands
done
4.处理用户输入
获取用户输入read
read命令选项
1.-p 可以在read命令行指定输入提示
read -p "Please enter your age: " age
2.-t 可以指定一个计时器 指定等待输入的秒数,当时间到了会返回一个非0的退出状态码
read -t 5 -p "Please enter your age: " name