2.1 shell 程序设计 1
【 实验内容】 】
使用 test 测试编写的 unload 程序,达到文件卸载的功能。
【 实验目的】 】
熟练掌握 shell 脚本的编写方法和技巧
熟练掌握判断语句的使用
【 实验平台】 】
PC 机,Ubuntu 操作系统,gcc 等工具
【实验步骤】
1、 编写 shell 脚本完成相应功能
2、 参考代码如下:
源码 unload.sh
#!/bin/sh
#unload - program to backup and remove files
#syntax: unload directory
#check arguments
if [ $# -ne 1 ]
then
echo "usage: $0 <directory>"
exit
fi
#check for valid directory name
if [ ! -d "$1" ]
then
echo "$1 is not a directory"
exit
fi
cd $1
ls -a | cpio -o > /dev/null
if [ $? -eq 0 ]
then
rm -rf *
else
echo "A problem has occured in creating backup"
Linux 系统实验手册
2
echo "The directory will not be ereased"
echo "Please check the backup device"
exit 3
fi
# end of unload
3、 修改文件属性为其添加可执行权限
chmod 777 unload.sh
4、 查看 test
ls test
a.out auto make Makefile malloc.c test test.bak test.c unload.sh
5、 执行脚本文件
./unload.sh test
6、 结果:
ls
结果目录中没有文件
2.2 shell 程序设计 2
【 实验内容】 】
编写脚本查看当前目录下文件属性(是普通文件还是目录)。
【 实验目的】 】
熟练掌握 shell 脚本的编写方法和技巧
熟悉 for 语句和判断语句 if…else…
【 实验平台】 】
PC 机,Ubuntu 操作系统,gcc 等工具
【实验步骤】
1、 编写 shell 脚本完成相应功能
2、 参考代码如下:
源码 file_or_dir.sh
#!/bin/sh
for i in *
do
if [ -f $i ]
then
echo "$i is a file"
elif [ -d $i ]
then
echo "$i is a directory"
fi
done
3、 修改文件属性为其添加可执行权限
chmod 777 file_or_dir.sh
4、 执行脚本文件
./file_or_dir.sh test
5、 结果:
case_and_if.sh is a file
file_or_dir.sh is a file
hello is a directory
unload.sh is a file
2.3 shell 程序设计 3
【 实验内容】 】
条件语句实例,实现文件的备份、恢复和卸载功能。
【 实验目的】 】
熟练掌握 shell 脚本的编写方法和技巧
【 实验平台】 】
PC 机,Ubuntu 操作系统,gcc 等工具
【实验步骤】
1、 编写 shell 脚本完成相应功能
Linux 系统实验手册
4
2、 参考代码如下:
源码 case_and_if.sh
#!/bin/sh
# Interactive program to restore, backup, or unload a directory
echo "Welcome to the menu driven Archive program"
while true
do
# Display a Menu
echo
echo "Make a Choice from the Menu below"
echo _
echo "1 Restore Archive"
echo "2 Backup directory"
echo "3 Unload directory"
echo "4 Quit"
echo
# Read the user's selection
echo -n "Enter Choice: "
read CHOICE
case $CHOICE in [1-3] )
echo # Read and validate the name of the directory
echo -n "What directory do you want? "
read WORKDIR
if [ ! -d "$WORKDIR" ]
then
echo "Sorry, $WORKDIR is not a directory"
continue
fi
# Make the directory the current working directory
cd $WORKDIR;;
*) echo "Sorry, $CHOICE is not a valid choice"
continue
esac
case "$CHOICE" in
1) echo "Restoring..."
cpio -i ;;
2) echo "Archiving..."
ls | cpio -o >/dev/null;;
3) echo "Unloading..."
ls | cpio -o >/dev/null;;
4) echo "Quitting"
break;;
esac
#Check for cpio errors
if [ $? -ne 0 ]
then
echo "A problem has occurred during the process"
if [ $CHOICE = 3 ]
then
Linux 系统实验手册
5
echo "The directory will not be erased"
fi
echo "Please check the device and try again"
continue
else
if [ $CHOICE = 3 ]
then
rm *
fi
fi
done
chmod 777 case_and_if
3、 执行脚本文件
./case_and_if.sh
4、 结果:
Make a Choice from the Menu below
_
1 Restore Archive
2 Backup directory
3 Unload directory
4 Quit
选择操作。结合上面两个例子查看最后结果。