
【实验目的】
(1)掌握shell的概念,了解shell的工作原理
(2)熟悉shell环境
(3)掌握基本的shell程序设计
【实验内容】
1.带一个(目录)参数,可浏览目录下的内容。(lsdir.sh)
实现功能:
(1)首先判断(if)是否带有参数(参考p207),若无则显示(echo)用法信息后,报错返回(exit);
(2)首先判断该参数是不是目录。若是则列目录的内容(ls),否则,提示用户不是目录,则显示警告信息后报错返回。
运行:设程序名为lsdir.sh,为其增加执行权后运行:
./lsdir.sh
./lsdir.sh dir #如果dir是个目录,则列其内容
./lsdir.sh file #若file是文件或不存在则给出警告后返回
#! /bin/bash
if [ $# -ne 1 ] #check if has 1 parameter
then
echo "Usage: $0 dir" #Display Usage
exit 1 #return 1
fi
if [ -d "$1" ] #if is a dir
then
ls -l $1/* #list the dir
exit 0
fi
echo "Warn: $1 is not a directory" #Warning message
exit 2 #return 2
2. 只用嵌套结构if-fi实现上述程序 (lsdirif.sh)
#! /bin/bash
if [ $# -ne 1 ]
then
echo "Usage: $0 dir"
exit 1
elif [ -d "$1" ]
then
ls $1/*
exit 0
else
echo "Warn: $1 is not a directory"
exit 2
fi
3、带数值参数,并可计算这些数值参数的和 (sum.sh)
#! /bin/bash
x=0
for y in $*
do
x=`expr $x + $y`
done
echo "The sum is: $x"
4、计算前n个正整数的和 (sum_n.sh)
注:此程序带有1个参数作为整数n,以计算1至n个正整数的和
#! /bin/bash
if [ $# -ne 1 ]
then
echo "Usage: $0 n"
exit 1
fi
x=0
y=1
while true
do
x=`expr $x + $y`
y=`expr $y + 1`
if [ $y -gt $1 ]
then
break
fi
done
echo "1+2+...+$1=$x"
5、编写Shell程序 (setmod.sh),在/home目录下建立10个目录,即user1~user10,并设置每个目录的权限,其中:
(1)文件所有者的权限为:读、写、执行
(2) 文件所有者所在组的权限为:读、执行
(3) 其他用户的权限为:读
#! /bin/sh
i=1
while [ $i -le 10 ]
do
if [ -d /home ];then
mkdir -p /home/user$i
chmod 754 /home/user$i
echo "user$i"
let "i=i+1"
else
mkdir /home
mkdir -p /home/user$i
chmod 754 /home/user$i
echo "user$i"
let "i=i+1"
fi
done
6.编写shell程序(deldir.sh),将第5题建立的10个目录(即user1~user10)自动删除,并显示删除目录信息
#! /bin/bash
i=1
while [ $i -le 10 ]
do
if [ -d /home/user$i ];then
rm -rf /home/user$i
echo "Directory /home/user$i deleted"
fi
let "i=i+1"
done
【实验重点】
1、掌握shell的概念
2、熟悉shell环境,掌握基本的shell程序设计
【实验步骤】
【实验总结】
【实验心得】
