目录
1.是什么?
2.写法
3.shell脚本语法
3.1第一个shell脚本
3.2交互式shell脚本
3.3shell脚本的数值计算
3.4test命令
3.5中括号【】判断符
3.6默认变量
4.shell脚本条件判断
4.1 if fi
4.2 if then else
4.3 if elif else
4.4 case
5.shell脚本函数
5.1 无参
5.2有参
6.shell循环
6.1while
6.2for
1.是什么?
在linux终端一条一条命令写起来很麻烦,因此需要一个一次性包含很多条命令的”命令“
2.写法
#!/bin/bash
3.shell脚本语法
3.1第一个shell脚本
1 #!/bin/bash
2
3 echo "hello world"
输出:hello world
3.2交互式shell脚本
通过read读取键盘输入的字符串
1 #!/bin/bash
2 echo "input your name:"
3 read name
4 echo "your name is:"$name
1 #!/bin/bash
2 read -p "input your age and height:"age height
3 echo "your age=$age,your height=$height"
3.3shell脚本的数值计算
1 #!/bin/bash
2 echo "input two num:"
3 read -p "first num:" first
4 read -p "second num:" second
5 total=$(($first+$second))
6 echo "$first + $second = $total"
3.4test命令
1.判断一个文件是否存在
1 #!/bin/bash
2 echo "input filename:"
3 read -p "filename is:" filename
4 test -e $filename && echo "$filename exist" || echo "$filename no exist"
2.判断字符串是否相等
1 #!/bin/bash
2 echo "input filename:"
3 read -p "first is:" first
4 read -p "second is:" second
5 test $first == $second && echo "==" || echo "!="
3.5中括号【】判断符
【】中只能输入 == 或者 !=
1 #!/bin/bash
2 echo "input filename:"
3 read -p "first is:" first
4 read -p "second is:" second
5 [ "$first" == "$second" ] && echo "==" || echo "!="
3.6默认变量
1 #!/bin/bash
2 echo "input name:" $0
3 echo "input param num:" $#
4 echo "first:" $0
5 echo "second:" $1
6 echo "whole num:" $@
7 echo "end:" $#
4.shell脚本条件判断
4.1 if fi
1 #!/bin/bash
2 read -p "input (Y/N)" value
3
4 if [ "$value" == "Y" ] || [ "$value" == "y" ];then
5 echo "your input is Y"
6 exit 0
7 fi
8
9 if [ "$value" == "N" ] || [ "$value" == "n" ];then
10 echo "your input is N"
11 exit 0
12 fi
4.2 if then else
1 #!/bin/bash
2 read -p "input (Y/N)" value
3
4 if [ "$value" == "Y" ] || [ "$value" == "y" ];then
5 echo "your input is Y"
6 exit 0
7 else
8 echo "your input is N"
9 exit 0
10 fi
4.3 if elif else
1 #!/bin/bash
2 read -p "input (Y/N)" value
3
4 if [ "$value" == "Y" ] || [ "$value" == "y" ];then
5 echo "your input is Y"
6 exit 0
7 elif [ "$value" == "Y" ] || [ "$value" == "y" ];then
8 echo "your input is N"
9 exit 0
10 else
11 echo "error"
12 fi
~
4.4 case
1 #!/bin/bash
2
3 case $1 in
4 "a")
5 echo "param is:a"
6 ;;
7 "b")
8 echo "param is:b"
9 ;;
10 *)
11 echo "error"
12 ;;
13 esac
5.shell脚本函数
5.1 无参
1 #!/bin/bash
2
3 function help(){
4 echo "help"
5 }
6 function close(){
7 echo "close"
8 }
9
10 case $1 in
11 "-h")
12 help
13 ;;
14 "-c")
15 close
16 ;;
17 esac
5.2有参
1 #!/bin/bash
2
3 print(){
4 echo "first 1:$1"
5 echo "second 2:$2"
6 }
7 print a b
6.shell循环
6.1while
先使用,再声明
1 #!/bin/bash
2 while [ "$value" != "close" ]
3 do
4 read -p "input :" value
5 done
6
7 echo "end while!"
6.2for
1 #!/bin/bash
2
3 for name in ljs1 ljs2 ljs3 ljs4
4 do
5 echo "name is: $name"
6 done
1 #!/bin/bash
2
3 read -p "input count:" count
4
5 total=0
6 for((i=0; i<=count;i++))
7 do
8 total=$(($total+$i))
9 done
10 echo "end : $total"
~