您的位置:首页 > 运维架构 > Linux

鸟哥的Linux私房菜基础学习篇(第二版)第十三章课后习题与答案

2012-05-04 15:23 609 查看
习题:

1、请建立一支 script ,当你执行该 script 的时候,该 script 可以显示: 1. 你目前的身份 (用 whoami ) 2. 你目前所在的目录 (用 pwd)。

答:

#!/bin/bash

echo -e "Your name is ==> `whoami`"

echo -e "The current directory is ==> `pwd`"

2、请自行建立一支程序,该程序可以用来计算『您还有几天可以过生日』啊??

答:

#!/bin/bash

read -p "Pleas input your birthday (MMDD, ex> 0709): " bir

now=`date +%m%d`

if [ "$bir" == "$now" ]; then

echo "Happy Birthday to you!!!"

elif [ "$bir" -gt "$now" ]; then

year=`date +%Y`

total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))

echo "Your birthday will be $total_d later"

else

year=$((`date +%Y`+1))

total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))

echo "Your birthday will be $total_d later"

fi

3、让用户输入一个数字,程序可以由 1+2+3... 一直累加到用户输入的数字为止。

答:

#!/bin/bash

read -p "Please input an integer number: " number

i=0

s=0

while [ "$i" != "$number" ]

do

i=$(($i+1))

s=$(($s+$i))

done

echo "the result of '1+2+3+...$number' is ==> $s"

4、撰写一支程序,他的作用是: 1.) 先查看一下 /root/test/logical 这个名称是否存在; 2.) 若不存在,则建立一个档案,使用 touch 来建立,建立完成后离开; 3.) 如果存在的话,判断该名称是否为档案,若为档案则将之删除后建立一个目录,文件名为 logical ,之后离开; 4.) 如果存在的话,而且该名称为目录,则移除此目录!

答:

#!/bin/bash

if [ ! -e logical ]; then

touch logical

echo "Just make a file logical"

exit 1

elif [ -e logical ] && [ -f logical ]; then

rm logical

mkdir logical

echo "remove file ==> logical"

echo "and make directory logical"

exit 1

elif [ -e logical ] && [ -d logical ]; then

rm -rf logical

echo "remove directory ==> logical"

exit 1

else

echo "Does here have anything?"

fi

5、我们知道 /etc/passwd 里面以 : 来分隔,第一栏为账号名称。请写一只程序,可以将 /etc/passwd 的第一栏取出,而且每一栏都以一行字符串『The 1 account is "root" 』来显示,那个 1 表示行数。

答:

#!/bin/bash

accounts=`cat /etc/passwd | cut -d':' -f1`

for account in $accounts

do

declare -i i=$i+1

echo "The $i account is \"$account\" "

done

本文所整理的答案出自 作者:鸟哥 原文地址:http://linux.vbird.org/linux_basic/fc4.php

转载时,请务必附上上述作者和出处!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐