命名规则
变量定义
name="sicong"
echo $name
num=10
echo ${num}
只读变量
删除变量
字符串
单引号/双引号
拼接字符串
my_name="sicong"
str1="hello, "$my_name" !"
str2="hello, ${my_name} !"
获取字符串长度
str="abcdef"
echo ${#str}
获取子字符串
str="1000phone is a good school"
echo ${str:1:3}
数组
规则
定义数组
读取数组中的元素
\#读取数组中的元素
echo ${arr1[2]}
\#如果要读取数组中的全部元素
echo ${arr2[@]}
\#或
echo ${arr2[*]}
注意{}的使用
获取数组元素的个数
length=${#arr1[@]}
echo $length
\# 或者
length=${#arr1[*]}
echo $length
获取数组单个元素的长度
lengthn=${#arr1[3]}
echo $lengthn
expr
运算符
数值运算符
expr 1 + 2
文件测试
-r file 可读
-w file 可写
-x file 可执行
-e file 是否存在
-s file 检测文件是否为空
-f file 是一个普通文件,并且有内容
-z 变量名 判断变量名是空字符串或者没有定义过
! 取反
! -z name 变量name的字符串长度非0
关系运算符
逻辑运算符
if语句
单分支
if [ 1 -lt 3 ] && [ 2 -lt 3 ];
then
echo "ok"
fi
注意if后的分号
双分支
多分支
case语句
echo ‘输入 1 到 4 之间的数字:‘
read aNum
case $aNum in
1) echo ‘你选择了 1‘
;;
2) echo ‘你选择了 2‘
;;
3) echo ‘你选择了 3‘
;;
4) echo ‘你选择了 4‘
;;
*) echo ‘你没有输入 1 到 4 之间的数字‘
;;
esac
循环语句
while循环
无参数无返回值
demo()
{
echo ‘hello world‘
}
#调用函数
demo
有返回值
有参数有返回值
#source hello.sh 将代码读入父shell直接执行
或. hello.sh
相当于python中的import
关联数组
类似python的字典
declare -A arr2=([name]=lotuslaw)
echo ${arr2[name]}
arr2[age]=10 # 赋值
echo $?
if [[ "$num" =~ [0-9]+ ]];then
if [ -r $a.txt ]
if test -r a.txt
n=$(expr $n + 1)
$(( n + 1 ))
sh -x test.sh调试代码
ctrl v shift i esc
ping -c 2 www.baidu.com
echo $?
awk
命令 2>/dev/null 1>a.txt
vim末行模式
sed
原文:https://www.cnblogs.com/lotuslaw/p/14801443.html