Linux Shell脚本学习

来源:互联网 发布:网络弹窗广告 编辑:程序博客网 时间:2024/05/20 00:17

昨天写了下linux的作业,除了第二题不明,剩下的两题都做出来了,下面是题解。到linux环境下会更新。

第一题:

#!/bin/bash

#Program accept 2 argments , to rename an alreadyexisting file to #another name, that has not existing, or #replace anotheralready

#existing one

 

argment=$#

test "$argment" -lt "2"&& echo "at least TWO arguments!!!" && exit 0

 

test ! -e $1 && echo "The filename'$1' Do NOT exist " && exit 0

 

test -e $2 && echo "The filename '$2'ALREADY exist , you want to replace it ?" && read -p "Inputyour choice:" choice

 

test "$choice" != "n"&&  mv $1 $2

 

第二题:

#/bin/bash

#show arguments in the command line

echo $0

while [ $# -ne 0 ]

do

echo $1

shift

done

 

 

第三题:

#!/bin/bash

# a menu having the submenu to show something aboutdate , cpu type etc

 

while [ "1" == "1" ]

do

clear

         echo"——————–menu—————–"

         echo"1) cpu info"

         echo"2) Memory info"

         echo"3) Exit"

         echo"——————————————–"

 

         echo-n "Enter you chose [1-3]:"

         readChose

case ${Chose} in

    1)

         while[ "1" == "1" ]

         do

         clear

                   echo"——————–cpu info—————–"

                   echo"1) date"

                   echo"2) cpu load"

                   echo"3) return to menu"

                   echo"0)exit"

                   echo"——————————————–—————–"

                   echo-n "Enter you chose [1-3]:"

         readChoice

         case${Choice} in

                   1)date +%T;;

                   2)uptime | awk -F '[,:]' '{print $7}';;

                   3)break;;

                   *)exit 0;;

        esac 

                   sleep0.5

                 done

                  ;;

 

     2)

         while[ "1" == "1" ]

         do

         clear

                   echo"——————–memory info—————–"

                   echo"1) Remained space of Memory"

                   echo"2) Remained space of Swap"

                   echo"3) return to menu"

                   echo"0) exit"

                   echo"——————————————–—————–——–"

                   echo-n "Enter you chose [0-3]:"

         readChoice

         case${Choice} in

                   1)free -m | awk '$1=="Mem:"{print $4}';;

                   2)free -m | awk '$1=="Swap:"{print $4}';;

                   3)break;;

                   *)exit 0;;

        esac 

         sleep0.5

        done

         ;;

             3) exit 0;;

             *) echo "This is not between1-3." ;;

esac

done

 

关于题目:

1. 编写一个实现文件名改名的Linux shell脚本(rename.sh),要求:
a) 该脚本使用两个命令行参数, 参数1为原文件名, 参数2为新文件名;
b) 脚本在运行时检查参数个数, 若参数少于2个则提示并退出运行;
c) 脚本应检查原文件名是否存在, 若不存在则提示错误并退出运行;
d) 脚本还应检查新文件名是否存在, 若存在, 则需要提示用户是否覆盖该文件, 若用户输入n则退出运行;
2. 编写一个shell脚本, 要求使用while循环语句逐行显示该脚本各命令行参数。
3. 编写一个脚本,产生一个二级的菜单。
第一级有三个功能项:cpu info , memory info ,exit
cpu info 第二级中有四个功能项:分别是显示当前日期,显示cpu的负载,返回主菜单,退出脚本;
memory第二级中有四个功能项:分别是显示内存剩余量,swap的剩余量,返回主菜单,退出脚本。

原创粉丝点击