Day-03:shell编程3个实例


实验题目:

1. 设计如下一个菜单驱动程序,保存为: menu.sh

Use one of the following options:

P:To display current directory

S:To display the name of running file $0

D:To display today's date and present time(如:2017-04-26 05:45:12)

L:To see the list of files in your present working directory

W:To see who is logged in

I:To see the ip address of this local machine

Q:To quit this program

Enter your option and hit:

要求对用户的输入忽略大小写,对于无效选项的输入给出相应提示。要求使用case

 

2. 编写一段bash shell程序,保存为:score.sh

根据键盘输入的学生成绩,显示相应的成绩登等级,

其中

60分以下为"Failed!",

60~69分为"Passed!",

70~79分为"Medium!",

80~89分为"Good!",

90~100为"Excellent!"。

如果输入超过100的分数,则显示错误分数提示。

如果输入负数,则退出程序,否则一直提示用户输入成绩

 

3. 编写一段bash shell程序,保存为file.sh

判断用户输入是否为有效目录路径。如果不是,提示该路径不是目录路径。如果是

,则依次输出该目录下的所有内容的 “文件路径_文件类型符号”形式。

直到用户输入q退出,否则一直提示用户输入。


1.创建一个菜单进行交互,主要考察对case的使用。注意:在case中是可以,在while中  || 是没用的,要用 -a 表示

#! /bin/sh

show () {
echo "Use one of the following options:"
echo "P:To display current directory"
echo "S:To display the name of running file"
echo "D:To display today's date and present time(如:2017-04-26 05:45:12)"
echo "L:To see the list of files in your present working directory"
echo "W:To see who is logged in"
echo "I:To see the ip address of this local machine"
echo "Q:To quit this program"
echo "Enter your option and hit:"
}

input="A"

while [ $input != "Q" -a $input != "q" ]
do

show
read input

case $input in
P | p) pwd
;;
S | s) echo $0
;;
D | d) date "+%Y-%m-%d %H:%M:%S"
;;
L | l) ls
;;
W | w) whoami
;;
I | i) ifconfig
;;
Q | q) echo "Bye!"
;;
*) echo "WRONG!!!"
esac

done

2.创建一个成绩判断器,主要联系if使用。注意,判断条件的数值是要用参数来辅助的!

#! /bin/sh

echo "please input the score:"
read input

while [ $input -ge 0 ] 
do
if [ $input -le 59 ]
then echo "Failed"
elif [ $input -le 69 ]
then  echo "Passed"
elif [ $input -le 79 ]
then echo "Medium"
elif [ $input -le 89 ]
then echo "Good"
elif [ $input -le 100 ]
then echo "Excellent"
else echo "WRONG!!!"
fi
echo "please input the score:"
read input

done
echo "Bye!"

3.文件存在判断。注意,目录的ls -l 跟普通文件显示是不一样的!条件判断用 逻辑符号 来辅助!

#! /bin/sh
input="S"

while [ $input != "q" ]
do

echo "input the filepath:"
read input

if [ -d $input ]
then for file in $input/*
do
if [ -d $file ]
then echo $file"_d"
else echo $file"_""`ls -l $file | cut -c 1`"
fi
done

elif [ $input = "q" ]
then exit 0
else echo "not Directory!"
fi

done
echo "Bye!"

综上,条件判断是个坑!【 】 要留空格,变量赋值不留空格。数值用参,字符串用逻辑符号,与或不是java的||和&&。


 

你可能感兴趣的:(Linux实验)