Linux学习笔记(6)——shell(3)
一、Shell流程控制
1.if else
(1)if语句语法格式:
if condition
then
command1
command2
…….
commandN
fi
(2)if else 语法格式:
if condition
then
command1
command2
…….
commandN
else
command
fi
(3)if else-if else 语法格式
if condition
then
command1
command2
…….
commandN
elif
command
else
command
fi
2.for 循环
for var in item1 item2…
do
command1
command2
…….
command
done
3.while 语句
while condition
do
command
done
4.until循环
until循环执行一系列命令直至条件为真时停止。与while循环的处理方式相反。只是会执行一次。
语法:
until condition
do
command
done
5.case 语句
case 值 in
模式1)
Command1
Command2
…
CommandN
;;
模式2)
Command1
Command2
…
CommandN
;;
esac
例:
运行结果:
esac 作为结束标记,每个case分支用右圆括号,用两个分号表示break。
6.跳出循环
break命令 允许跳出所以循环(终止执行后面的所有循环)
continue命令 与break命令类似,但它不会跳出所以循环,仅跳出当前循环。
二、Shell函数
函数定义格式:
[ function ] funname [ ( ) ]
{
action;
[ retuen int ; ]
}
说明:
- 1.可以写成function fun(),也可直接用fun()定义,不带任何参数。
- 2.参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 return 后跟数值 n(0-255)
例1:不带 return
执行结果:
例2:带return
执行结果:
函数返回值在调用该函数后通过$? 来获得。
注意:所有函数在使用前必须定义。在调用函数时仅使用其函数名即可。
函数参数
调用函数时可以向其传递参数。在函数内部通过$n的形式来获取参数的值。
例:
执行结果:
注:$# :传递到脚本的参数个数
$* :以一个单字符串显示所有向脚本传递的参数
三、Shell 输入/输出重定向
重定向命令:
Command > file 将输出重定向到file
Command < file 将输入重定向到file
Command >> file 将输出以追加的方式重定向到file
n > file 将文件描述符为n的文件重定向到file
n >> file 将文件描述符为n的文件以追加的方式重定向到file
n > & m 将输出文件m和n合并
n < & m 将输入文件m和n合并
<< tag 将开始标记tag和结束标记tag之间的内容作为输入
注意:文件描述符 0 通常为 标准输入,1是标准输出,2是标准错误输出。