lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shnum1=100num2=200if[$num1 -eq $num2]thenecho"num1 eq num2"elseecho"num1 no eq num2"fi
lng@ubuntu:~/myshell$ ./myTest.sh
num1 no eq num2
lng@ubuntu:~/myshell$
lng@ubuntu:~/myshell$ ls
a.txt b.txt dire myTest.sh
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shiftest -f a.txt;thenecho"a.txt is file"fiif[ -f b.txt ];thenecho"b.txt is file"fiif[ -d dire ];thenecho"dire is directory"fi
lng@ubuntu:~/myshell$ ./myTest.sh
a.txt is file
b.txt is file
dire is directory
lng@ubuntu:~/myshell$
3 控制结构
3.1 if语句
if语句非常简单:它对某个命令的执行结果进行测试,然后根据测试结果有条件地执行一组语句。
语法结构
if condition
then
statements
else
statements
fi
测试用例
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shecho"please input yes or no!"#读取终端输入read temp
if[$temp="yes"]thenecho"you input is yes"elseecho"you input is no"fi
lng@ubuntu:~/myshell$ ./myTest.sh
please input yes or no!yes
you input is yes
lng@ubuntu:~/myshell$
3.2 elif
语法结构
if condition1
then
statements
elif condition2
then
statements
else
statements
fi
测试案例
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shecho"please input yes or no!"#读取终端输入read temp
if[$temp="yes"]thenecho"you input is yes"elif[$temp="no"]thenecho"you input is no"elseecho"you input unknow"fi
lng@ubuntu:~/myshell$ ./myTest.sh
please input yes or no!
fff
you input unknow
lng@ubuntu:~/myshell$
3.3 for语句
我们可以用for结果来循环处理一组值,这组值可以是任意字符串的集合。
语法结构
forvariablein values
do
statements
done
测试案例
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shforfruitin apple bnana pear;doecho"I like $fruit"done
lng@ubuntu:~/myshell$ ./myTest.sh
I like apple
I like bnana
I like pear
lng@ubuntu:~/myshell$
case variable in
pattern [| pattern ]...) statements;;
pattern [| pattern ]...) statements;;...
esac
测试用例
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shecho"please input num"read buf
case"$buf"in
one)echo"input is one";;
two)echo"input is two";;
three)echo"input is three";;
four)echo"inpuit is four";;esac
lng@ubuntu:~/myshell$ ./myTest.sh
please input num
three
input is three
lng@ubuntu:~/myshell$
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shecho"please input yes or no"read buf
case"$buf"inyes|y|YES|Y)echo"input is yes";;
n*|N*)echo"input is no";;esac
lng@ubuntu:~/myshell$ ./myTest.sh
please input yes or no
y
input is yes
lng@ubuntu:~/myshell$ ./myTest.sh
please input yes or no
noo
input is no
lng@ubuntu:~/myshell$
4 函数
如果需要编写大型的shell脚本程序,就要用到函数
一个简单的函数
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shmyFunc(){echo"this is myFunc"}echo"------"
myFunc
echo"++++++"
lng@ubuntu:~/myshell$ ./myTest.sh
------
this is myFunc
++++++
lng@ubuntu:~/myshell$
函数传入参数
lng@ubuntu:~/myshell$ cat myTest.sh
#! /bin/shmyFunc(){echo"param num is $#"echo"param 1 is $1, param 2 is $2"echo"this is myFunc"}echo"------"
myFunc aaa bbb
echo"++++++"
lng@ubuntu:~/myshell$ ./myTest.sh
------
param num is 2
param 1 is aaa, param 2 is bbb
this is myFunc
++++++
lng@ubuntu:~/myshell$