文章目录-练习2
- 前言
- 1.编写shell脚本程序,完成如下功能: 输出hello world !
- 2.编写shell脚本程序,完成如下功能: 输入你的姓名,输出 hello, nice to meet you 你的姓名!
- 3.编写shell脚本程序,完成如下功能: 输出当前登录用户的身份及当前所在目录(使用whoami及pwd命令)
- 4.编写shell脚本程序,完成如下功能: 输入一个合法的目录名, 判断当前目录是否存在该目录, 如果不存在则创建目录, 如果存在则输出提示信息
- 5.编写shell脚本程序,完成如下功能:(使用date命令) 输入你的姓名,根据当前系统时间输出如下信息: 如果当前系统时间<12点, 则输出: good morning, 你的姓名 如果当前系统时间>12点 并且<15点, 则输出good afternoon, 你的姓名 如果当前系统时间> 15点, 则输出good bye, 你的姓名
- 6.编写shell脚本程序,完成如下功能:(使用date命令) 输入一个人的出生日期,计算此人今年多少岁, 并计算今天距此人今年生日还有多少天
- 7.编写shell脚本程序,完成如下功能: 输入一个整型数a, 计算1+2+...+a之和并将其输出
- 总结
前言
# Shell脚本练习
1.编写shell脚本程序,完成如下功能: 输出hello world !
echo "hello world!"
2.编写shell脚本程序,完成如下功能: 输入你的姓名,输出 hello, nice to meet you 你的姓名!
read -p "输入你的姓名" name
echo "hello,nice to meet you $name"
3.编写shell脚本程序,完成如下功能: 输出当前登录用户的身份及当前所在目录(使用whoami及pwd命令)
echo "当前登录用户的身份:"
whoami
echo "当前所在的目录:"
pwd
4.编写shell脚本程序,完成如下功能: 输入一个合法的目录名, 判断当前目录是否存在该目录, 如果不存在则创建目录, 如果存在则输出提示信息
read -p "请输入一个目录名:" dir
if [ -e $dir ];then
echo "当前目录下存在该目录"
ls -l ./
else
echo "当前目录下不存在该目录,将创建"
mkdir -p $dir
ls -l ./
fi
5.编写shell脚本程序,完成如下功能:(使用date命令) 输入你的姓名,根据当前系统时间输出如下信息: 如果当前系统时间<12点, 则输出: good morning, 你的姓名 如果当前系统时间>12点 并且<15点, 则输出good afternoon, 你的姓名 如果当前系统时间> 15点, 则输出good bye, 你的姓名
time=`date +%l`
read -p "输入你的姓名:" name
if [ $time < 12 ]
then
echo "good morning,$name"
elif [ $time > 12 -o $time < 15]
then
echo "good afternoon,$name"
elif [ $time > 15 ]
then
echo "good bye,$name"
fi
6.编写shell脚本程序,完成如下功能:(使用date命令) 输入一个人的出生日期,计算此人今年多少岁, 并计算今天距此人今年生日还有多少天
read -p "请输入你的生日日期(格式:`date +'%F %H:%M:%S'`)" birthday
read -p "请输入你生日的月份:" month1
read -p "请输入你生日的是哪个月份的第几天:" day1
first_stamp+`date -d "$birthday" +%s` #计算指定日期的时间戳
today_stamp=`date +%s` #计算当天的时间戳
let day_stamp=($today_stamp - $first_stamp) #当天的时间戳减去指定的时间戳
let day=($day_stamp/86400)
let year=($day/365)
month2=`date +%F | cut -d"-" -f2`
day2=`date +%F | cut -d"-" -f3`
let month3=($month2 - $month1)
let day3=($day2 - $day1)
let day4=($month3*30 + $day3)
echo "此人今年位:$year岁"
echo "今天距此人今年生日还有$day4天"
7.编写shell脚本程序,完成如下功能: 输入一个整型数a, 计算1+2+…+a之和并将其输出
read -p "Enter a num:" num
sum=0
for i in `seq 1 $num`
do
sum=$((sum+$i))
done
echo "$sum is sum"