实验六:shell编程
实验步骤
- 登录系统。
a.使用实验一创建的用户名和密码登录系统。
b.打开终端应用。
- 基础知识:
a.理解shebang语句的作用。
b.掌握执行shell脚本的两种方式:
shell名 脚本名
可执行脚本
c.对于以下脚本,分别采用两种方式执行。
- 创建一个shell脚本service,完成如下功能:
a.清屏。
b.跳两行。
c.显示当前的日期和时间。
d.显示当前用户数量。
e.蜂鸣,然后显示消息“Now at your service”。
答案:
clear
echo -e "\n\nDateTime:`date`"
echo -e "\nUser Number:`who | wc -l`"
echo -e "\07\nNow at you service"
- 创建一个shell脚本max,要求如下:
a.用户三个数字。
b.获取其中最大的数字,并显示。
答案:
if [ $1 -gt $2 ]
then
max=$1
else
max=$2
fi
if [ $max -lt $3 ]
then
max=$3
fi
echo "The max is: $max"
exit 0
- 创建一个shell脚本sum,要求如下:
a.使用方式为:$ sum a b,其中a和b代表两个数字,a<b。
b.功能是计算从a到b的累加和。
c.在屏幕上显示:a + … + b = result。result为累加和。
答案:
if [ $1 -ge $2 ]
then
exit 1
fi
a=$1
b=$2
sum=0
while [ $a -le $b ]
do
sum=`expr $sum + $a`
a=`expr $a + 1`
done
echo "$1+…+$2=$sum"
exit
- 创建一个shell脚本check,要求如下:
a.检查当前主目录中是否存在.profile文件,输出检查结果。
b.如果不存.profile文件,则创建一个.profile文件。
c.在.profile的末尾追加如下两行信息:
echo “Hello, Welcome to Linux!”
echo “Current Date and Time: [`date`]”
答案:
cd
if [ ! -e .profile ]
then
touch .profile
echo "Not exist .profile"
else
echo "Exist .profile"
fi
echo 'echo "Hello, Welcome to Linux!"' >> .profile
echo 'echo "Current Date and Time:`date`"' >>.profile
echo "Write Success!"
exit 0