Linux shell编程参考文档
(2)设置权限
[root@localhost bin]#chmod +x test12 (3)执行
[root@localhost bin]#./ test12 /root/.Trash/abc~ has been deleted! /root/.Trash/abc1 has been deleted!
(1)用 vi 编辑脚本程序 test13
#! /bin/Bash total =0
for((j=1;j<=100;j++)); do
实例 1-14:求从 1~100 的和。
[root@localhost bin]#vi test13
total=`expr $total + $j` done
echo “The result is $total” (2)设置权限
[root@localhost bin]#chmod +x test13 (3)执行
[root@localhost bin]#./ test13 The result is 5050
for 语句中的双括号不能省,最后的分号可有可无,表达式 total=`expr $total + $j`的加 号两边的空格不能省,否则会成为字符串的连接。
注意:
1-6-2 while 循环
语法:
while 表达式 do
操作 done
只要表达式为真,do 和 done 之间的操作就一直会进行。
实例 1-15:用 while 循环求 1~100 的和。
(1)用 vi 编辑脚本程序 test14 [root@localhost bin]#vi test13 total =0
Linux Shell编程 第17页/共26页
Linux Shell 编程参考文档
num=0
while((num<=100));
do
total=`expr $total +$ num` num=`expr $num + 1`
done
echo “The result is $total”
(2)设置权限
[root@localhost bin]#chmod +x test14
(3)执行 [root@localhost bin]#./ test14 The result is 5050
1-6-3 until 循环
语法:
until 表达式 do 操作 done
重复 do 和 done 之间的操作直到表达式成立为止。
实例 1-16:用 until 循环求 1~100 的和。
(1)用 vi 编辑脚本程序 test15 [root@localhost bin]#vi test15 total =0
num=0
until [$num –gt 100] do total=`expor $total +$ num`
num=`expr $num + 1`
done
echo “The result is $total”
(2)设置权限
[root@localhost bin]#chmod +x test15
(3)执行 [root@localhost bin]#./ test15 The result is 5050
Linux Shell编程 第18页/共26页
Linux shell编程参考文档
1-7 条件结构语句
?? Shell 的条件结构语句
Shell 程序中的条件语句主要有 if 语句与 case 语句。
1-7-1 if 语句
语法: if 表达式 1 then 操作
elif 表达式 2 then 操作
elif 表达式 3 then 操作 ?? else 操作 fi
Linux 里的 if 的结束标志是将 if 反过来写成 fi;而 elif 其实是 else if 的缩写。其中, elif 理论上可以有无限多个。
实例 1-17:判断1-10之间的数,如果是奇数就打印出来。
(1)用 vi 编辑脚本程序 test16 [root@localhost bin]#vi test16 for((j=0;j<=10;j++)) do
fi
if(($j%2==1)) then
echo “$j”
done
(2)设置权限
[root@localhost bin]#chmod +x test16 (3)执行
[root@localhost bin]#./ test16 13579
Linux Shell编程 第19页/共26页
Linux Shell 编程参考文档
1-7-2 case 语句
语法: case 表达式 in 值 1|值 2) 操作;; 值 3|值 4) 操作;; 值 5|值 6) 操作;;
*) 操作;; esac
case 的作用就是当字符串与某个值相同是就执行那个值后面的操作。如果同一个操作对于 多个值,则使用“|”将各个值分开。在 case 的每一个操作的最后面都有两个“;;”分号是必需 的。
实例 1-18:Linux 是一个多用户操作系统,编写一程序根据不同的用户登录输出 不
同的反馈结果。
(1)用 vi 编辑脚本程序 test17 [root@localhost bin]#vi test17 #!/bin/sh case $USER in
beechen)
echo “You are beichen!”;; liangnian)
echo “You are liangnian”; //注意这里只有一个分号 echo “Welcome !”;; //这里才是两个分号 root)
echo “You are root!”;echo “Welcome !”;; //将两命令写在一行,用一个分号作为分隔符 *)
echo “Who are you?$USER?”;; easc
(2)设置权限
[root@localhost bin]#chmod +x test17 (3)执行
[root@localhost bin]#./ test17 You are root Welcome!
Linux Shell编程 第20页/共26页
Linux shell编程参考文档
1-8 在 Shell 脚本中使用函数
?? Shell 的函数
Shell 程序也支持函数。函数能完成一特定的功能,可以重复调用这个函数。 函数格式如下: 函数名( ) { 函数体
} 函数调用方式为 函数名 数列表
参
结果。
实例 1-19:编写一函数 add 求两个数的和,这两个数用位置参数传入,最后输出
(1)编辑代码
[root@localhost bin]#vi test18 #!/bin/sh add() { a=$1 b=$2
z=’expr $a + $b’
echo “The sum is $z” }
add $1 $2 (2)设置权限
[root@localhost bin]#chmod +x test18 (3)执行 [root@localhost bin]#./ test18 10 20 The sum is 30
函数定义完成后必须同时写出函数的调用,然后对此文件进行权限设定,在执行此文件。
注意:
Linux Shell编程 第21页/共26页