Shell脚本中的语法与C语言类似
一、shell的一些基本了解
1.shell脚本的后缀名为“ .sh”
2.shell文本以 #!/bin/bash 开头。#!是一个约定的标记,它告诉这个系统这个脚本需要什么解释器来执行。
3.shell文本通用的两种执行方式:
(1) /bin/bash test.sh
(2)对test.sh增加可执行权限 chmod u+x test.sh , 然后 ./test.sh 即可执行
二、shell的基本语法:
1.条件测试
(1)常见的测试命令包含test 或 [
(2)测试类型不同用的命令不同
—–>整数测试:-eq (==) , -ne(!=) , -lt(<) , -gt(>) , -le(<=) ,-ge(>=)
—–>字符串测试:== != -z(字符串为空) -n(字符串不为空)
—–>文件测试: -d (目录文件) -f(普通文件) -b(块设备) -c(字符文件)
2.测试用例
#!/bin/bash
//定义函数
function intAdd()
{
let data=$1+$2
echo $data
}
//三种死循环
#until false
#do
# echo "hello world"
#done
#while true
#do
# echo "hello"
#done
#for ((;;))
#do
# echo "hello"
#done
#i=0
#until [ $i -ge 10 ] //当i的值不大于等于10为真
#do
# echo "hello $i"
# let i++
#done
#i=0
#while [ $i -le 5 ]
#do
# echo "hello $i"
# ((i++))
# #let i++
#done
#for i in {a..e} {1..5}
#do
# echo "hello $i"
#done
#for i in {a..z}
#do
# echo "hello $i"
#done
#for i in {1..20}
#do
# echo "hello $i"
#done
//循环语句
#for (( i=0; i<=10; i++ ))
#do
# echo "hello $i"
#done
//类似switch ... case 语句
#case $1 in
# 'start' )
# echo "start ... done"
# ;;
# 'stop' )
# echo "stop ... done"
# ;;
# 'result' )
# echo "result ... done"
# ;;
# 'status' )
# echo "status ... done"
# ;;
# * )
# echo "default"
# ;;
#esac
//懒逻辑
#printf "data:"
#read data
#[ $data -eq 100 ] && echo "yes1"
#[ $data -eq 100 ] || { echo "yes2"
#}
#printf "data:"
#read data
#[ $data -eq 100 ] && echo "yes"
#[ $data -eq 100 ] && { echo "yes"
#}
//不能进行空操作,":"表示真
#printf "data:"
#read data
#if [ $data -eq 100 ];then
# :
#else
# echo "AAAAAA"
#fi
#printf " file name:"
#read filename
#
#if grep -Eq '222' "$filename";then
# echo "yes"
#else
# echo "no"
#fi
//循环嵌套
#printf "data:"
#read data
#if [ $data -lt 100 ];then
# if [ $data -eq 50 ];then
# echo "data is -eq 50"
# elif [ $data -lt 50 ];then
# echo "data is -lt 50"
# else
# echo "data -gt 50 and -lt 100"
# fi
#else
# echo "data is great than 100"
#fi
//if语句
#printf "string:"
#read mystring
#if [ "X$mystring" == "Xhello" ];then
# echo "get hello"
#fi
//
#printf "string:"
#read mystring
#if [ "X$mystring" == "Xhello" ]
#then
# echo "get hello"
#fi
//多条语言测试
#printf "data1:"
#read data1
#printf "data2:"
#read data2
#[ $data1 -eq 100 -o $data2 -eq 200 ]
#echo $?
#printf "data1:"
#read data1
#printf "data2:"
#read data2
#[ $data1 -eq 100 -a $data2 -eq 200 ]
#echo $?
#read mysqtring
#[ !"X$string"=="Xhello" ]
#echo $?
//测试文件
#[ -c /dev/tty ] #字符设备
#echo $?
#[ -b /dev/sda ] #块设备
#echo $?
#[ -f /test.sh ] #普通文件
#echo $?
#[ -d / ] #目录
#echo $?
//测试字符串,添加X防止对空串判断出错
#read mystring
#[ "X$mystring" == "hello" ]
#echo $?
//测试字符串
#read mystring
#[ $mystring == "hello" ]
#echo $?
#[ $mystring != "hello" ]
#echo $?
#[ -z $mystring ] #是否为空串
#echo $?
#[ -n $mystring ] #是否为非空串
#echo $?
//测试整数
#read myint
#test $myint -eq 100
#echo $?
#
#[ $myint -ne 100 ]
#echo $?
#[ $myint -lt 100 ]
#echo $?
#[ $myint -gt 100 ]
#echo $?
#[ $myint -le 100 ]
#echo $?
#[ $myint -ge 100 ]
#echo $?