1.简历一个shell文件
#! /bin/sh
echo "Hello World!"
文件保存test.sh
2.运行
方法1:将文件拖到终端
➜ ~ git:(master) ✗ /Users/summer/Desktop/test.sh
zsh: permission denied: /Users/summer/Desktop/test.sh
没有权限,进入目录,修改权限
chmod 777 test.sh
方法2:输入 ./test.sh
➜ Desktop git:(master) ✗ ./test.sh
Hello World!
语法
1.变量赋值用=,两边不能有空格
2.输出 echo,使用$,否则直接输出变量名
echo test
echo $test
echo ${test}
输出
➜ Desktop git:(master) ✗ ./test.sh
test
a
a
3.只读变量readonly
4.删除变量unset,删除变量后不能再次使用,不能删除只读变量
5.单引号,双印号
单引号中不能再加单引号,单引号中的变量无效
双印号可以有转义字符,变量有效
#! /bin/sh
string=a
oldString='Hello $string'
oldString_1='Hello ${string}'
newString="Hello $string"
newString_1="Hello ${string}"
echo $oldString
echo $oldString_1
echo $newString
echo $newString_1
➜ Desktop git:(master) ✗ ./test.sh
Hello $string
Hello ${string}
Hello a
Hello a
6.获取字符串长度
test=a
echo ${#test}
1
7.截取字符串
test="abcd"
echo ${test:1:4}
bcd
8.获取字符串位置【从1开始,不是0开始】
string='running'
echo `expr index "$string" r`
1
9.数组
test=(1 aa 3)
echo ${test[@]} //输出数组
echo ${test[1]} //输出底标为1的元素
echo ${#test[@]} //输出数组长度
echo ${#test[1]} //输出底标为1的元素的长度
➜ Desktop git:(master) ✗ ./test.sh
1 aa 3 //输出数组
aa //输出底标为1的元素
3 //输出数组长度
2 //输出底标为1的元素的长度
10.算数运算符
expr 符号两侧为空格 语句反印号
test=
expr 2 + 2
echo ${test}
a=expr 2 - 1
echo $a
echoexpr $test + $a
➜ ~ git:(master) ✗ /Users/summer/Desktop/test.sh
4
1
5代码中的 [] 执行基本的算数运算
a=$[1+2]
echo ${a}
3
11输入命令并显示
read name
echo "$name It is a test"
ok //输入
ok It is a test //输出
参数说明:
-p 输入提示文字
-n 输入字符长度限制(达到6位,自动结束)
-t 输入限时
-s 隐藏输入内容
read -p "请输入一段文字:" -n 6 -s password
echo "\npassword is $password"
➜ Desktop git:(master) ✗ ./test.sh
请输入一段文字:\npassword is 123456
12.与 -a 或 -o 非 !
13.if
if
a=20
b=20
if [ $a -lt $b ]
then echo a
elif [ $a -gt $b ]
then
echo b
elif [ $a == $b ]
then
echo a==b
fi
14.算数运算符
expr 符号两侧为空格 语句反印号
test=
expr 2 + 2
echo ${test}
a=expr 2 - 1
echo $a
echoexpr $test + $a
➜ ~ git:(master) ✗ /Users/summer/Desktop/test.sh
4
1
52.代码中的 [] 执行基本的算数运算,符号两侧不需要空格
a= [1+2]echo [ 1 + 2 ] e c h o {a}
3
输入命令并显示
read name
echo "$name It is a test"
ok //输入
ok It is a test //输出
参数说明:
-p 输入提示文字
-n 输入字符长度限制(达到6位,自动结束)
-t 输入限时
-s 隐藏输入内容
read -p "请输入一段文字:" -n 6 -s password
echo "\npassword is $password"
➜ Desktop git:(master) ✗ ./test.sh
请输入一段文字:\npassword is 123456
15.与 -a 或 -o 非 !
16.if
a=20
b=20
if [ $a -lt $b ]
then echo a
elif [ $a -gt $b ]
then
echo b
elif [ $a == $b ]
then
echo a==b
fi
17.for
for (( i = 0; i < 100; i++ ));
do
echo $i
done
for i in {1..100};
do
echo $i
done
for i in `seq 1 20`
do
echo $i
done
18.while:输入用户名和密码
n="name"
p="123asd"
echo "请输入用户名"
read name
while [ "$name" != "$n" ]
do
echo "用户名错误"
echo "请重新输入用户名"
read name
done
echo "请输入密码"
read -s password
while [ $password != $p ]
do
echo "密码错误"
echo "请重新输入密码"
read -s password
done
echo success