shell脚本


1.什么是shell脚本

就是把很多的linux命令放在一个文件一起从上到下执行

2.shell脚本写法

#!/bin/bash

表示使用bash

3.shell脚本语法

read输入

#!/bin/bash
echo "please input:"
read name
echo "your nmae" $name

也可以

#!/bin/bash
read -p "please input:"name age
echo "your nmae" $name

数值计算

#!/bin/bash
read -p "please input:"first second
total=$($first + $second) //=两边不能用空格
echo "$first + $second = $total " 

test

用于查看文件是否存在、权限等信息,可以进行数值,字符,文件三方面的测试
cmd1 && cmd2
并不是与的关系,是先执行cmd1,成功了执行cmd2,如果cmd1执行失败了,则cmd2也不会执行
cmd1 || cmd2 当cmd1执行正确就不执行cmd2,如果cmd1错误就cmd2

#!/bin/bash
echo "please input filename: "
read -p "file name = " filename
test -e $filename && echo "$filename exist" || "$filename no exist"

查看两个字符串是否相等:

#!/bin/bash
echo "please input string: "
read -p "first string = " first
read -p "second string = " second
test $first == $second && echo "equal" || " no equal"

-e 查看文件名,存在就为真

[]判断符

#!/bin/bash
echo "please input string: "
read -p "first string = " first
read -p "second string = " second
[ "$first" == "$second" ] && echo "equal" || " no equal"

中括号两端必须加空格!
字符串必须加双引号:
假如改成
[ $first == "a b" ] && echo "equal" || " no equal"
first = a b
就变成 a b == "a b"前面的a就没关系了

默认变量

$0 - $n:表示shell脚本的参数,包括他自己本身。shell本身为0
$# : 表示最后一个参数标号
$@: 表示1---n

#!/bin/bash
echo "file name: " $0
echo "total param num: " $#
echo "whole param : " $0
echo "first param : " $1
echo "second param : " $2

if

#!/bin/bash
read -p "please input : " value

if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
   echo "Y"
   exit 0
fi

elif [ "$value" == "N" ] || [ "$value" == "n" ]; then
   echo "n"
   exit 0
fi

else 
   echo "?"
   exit 0
fi

case

#!/bin/bash
read -p "please input : " value

case $1 in 
	"a")
		echo " = a"
		;;
	"b")
		echo " = b"
		;;
	*) //其他,不能用双引号
		echo "no"
		;;
esac

函数

function fname(){
	//函数代码段
}
#!/bin/bash

function help(){
	echo "this is help"
}
function close(){
	echo "close!"
}
case $1 in 
	"h")
		help
		;;
	"c")
		close
		;;
	*) 
		echo "no"
		;;
esac

传参的时候加 -h或者-c

#!/bin/bash

function print(){
	echo "param 1 $1"
	echo "param 2 $2"
	echo "param 3 $3"
}
print a b c //这样传参

循环

while:

#!/bin/bash

while [ "$value" != "close" ]
do
	read -p "input:" value
done

echo "stop"

for:

#!/bin/bash

for name in szm szm1 szm2
do
	echo "your name" name
done
#!/bin/bash

read -p "input:" count
total = 0
for((i = 0; i <= count; i = i+1))
do
	total=$(($total + $i))
done

echo "total = " $total