本文总结自《shell从入门到精通》
1 新建bash脚本
新建脚本文本 test1.sh
#! /bin/bash
echo "what's your name?"
read PERSON
echo "Hello, $PERSON"
然后依次在命令行输入
cd /home/zhangjin/zhangjinming
chmod +x ./test.sh #使脚本具有执行权限
./test.sh #执行脚本
2 基本语法
##1 shell脚本的参数
#$表示命令行参数的个数
#n表示脚本的第n个参数
##2 运算符
string1 = string2 判断两个字符串是否相等
-z string 判断string是否为空串
num1 -eq num2 比较num1与num2是否相等
num1 -ne num2 不等于
num1 -gt num2 大于
num1 -lt num2 小于
num1 -ge num2 大于等于
num1 -le num2 小于等于
3 if else 语句,注意fi用来结束
#! /bin/bash
echo "Please enter a score:"
read score
#保证非空
if [ -z "$score" ]
then
echo "you enter nothing. please enter a score"
read score
else
if [ "$score" -lt 0 -o "$score" -gt 100 ]
then
echo "the score should be 0~100"
read score
else
if [ "$score" -ge 90 ]
then
echo "the grade is a"
elif [ "$score" -ge 80 ]
then
echo "the grade is b"
fi
fi
fi
##4 流配符
[:punct:]:标点符号
[:lower:]:小写字母
[:upper:]:大写字母
[:digit:]:数字
##5 循环结构
#! /bin/bash
i=1
while [[ "$i" -lt 10 ]]
do
let "square=i*i"
echo "$i*$i=$squre"
let "i=i+1"
done
3 正则表达式
##1 元字符
str=‘ls /etc | grep “^po”’ #列出/etc目录中的以字母po开头的文件
str=‘ls /etc | grep “conf$”’ #列出/etc目录中以conf结尾的文件名
str=‘ls /etc | grep “samba.”’ #圆点.可以代替任意一个字符
str=‘ls /etc | grep “^rc[0-9]”’ #筛选rc0、rc1、rc2等文件
str=‘grep “o[ru]” demo3.txt’ #在demo.txt中匹配含有字符or或ou的文本行