您好,欢迎来到年旅网。
搜索
您的当前位置:首页计算机系统平台实验2指导书

计算机系统平台实验2指导书

来源:年旅网
实验二 Shell编程基础

一、实验目的

掌握Shell编程的一般方法,能运用常用的Shell命令编写简单的Shell程序,并能在LINUX系统所提供的bin/sh或bin/bash下正确的运行。

二、实验内容

1.用Shell命令确定自己登录的是何种Shell。

2.创建一个Shell脚本,通常要注意以下几个问题:

 可以使用任何文本编辑器制作脚本,如emacs、vi、gedit等。  程序通常以下面的行开始(必须在文件的第一行):

#!/bin/bash

 改变文件属性为可读可执行 chmod +rx filename  ./filename 来执行编写的脚本

请你创建一个shell脚本程序,输入圆半径值, 输出圆面积值,并在Linux下运行。 #!/bin/bash PI=3.14159

echo “请输入圆的半径:” read r

echo “圆的面积为:” echo $PI*$r*$r | bc

3. 在Shell中可以使用语句控制程序流程,请你阅读如下Shell脚本,并分析其执行结果: #!/bin/bash result=0 num=1

while test $num -le 10 do result=`expr $result + $num` num=`expr $num + 1` done

echo \"result=$result\"

若将其功能扩展为:计算1+2+...+n(n作为文件名参数输入),应该如何实现? while test $num -le $1

4.在shell中除了可以定义变量之外,还可以定义函数。通常,我们将函数看成是脚本中的一段代码,在使用函数之前必须先定义该函数,使用时利用函数名直接调用。

分析以下shell脚本的功能,写出执行过程与结果。 #!/bin/bash

function square {

local sq # sq is local to the function let \"sq=$1 * $1\"

echo \"Number to be squared is $1.\" echo \"The result is $sq \" }

echo \"Give me a number to square. \" read number

value_returned=$(square $number) # Command substitution echo \"$value_returned\"

编写一个函数,完成最大公约数的求解,并在shell脚本中调用。

5. 请编写一个shell脚本,完成密码的输入与验证,假设已知密码为”secret”。

三、实验过程

请写出每个实验的shell命令或脚本,并给出操作过程和执行结果。

1.用Shell命令确定自己登录的是何种Shell。

2.创建一个Shell脚本,通常要注意以下几个问题:

 可以使用任何文本编辑器制作脚本,如emacs、vi、gedit等。  程序通常以下面的行开始(必须在文件的第一行):

#!/bin/bash

 改变文件属性为可读可执行 chmod +rx filename  ./filename 来执行编写的脚本

请你创建一个shell脚本程序,输入圆半径值, 输出圆面积值,并在Linux下运行。 #!/bin/bash PI=3.14159

echo “请输入圆的半径:” read r

echo “圆的面积为:” echo $PI*$r*$r | bc

3. 在Shell中可以使用语句控制程序流程,请你阅读如下Shell脚本,并分析其执行结果:

#!/bin/bash result=0 num=1

while test $num -le 10 do result=`expr $result + $num` num=`expr $num + 1` done

echo \"result=$result\"

若将其功能扩展为:计算1+2+...+n(n作为文件名参数输入),应该如何实现? while test $num -le $1

4.在shell中除了可以定义变量之外,还可以定义函数。通常,我们将函数看成是脚本中的一段代码,在使用函数之前必须先定义该函数,使用时利用函数名直接调用。

分析以下shell脚本的功能,写出执行过程与结果。 #!/bin/bash

function square {

local sq # sq is local to the function let \"sq=$1 * $1\"

echo \"Number to be squared is $1.\" echo \"The result is $sq \" }

echo \"Give me a number to square. \" read number

value_returned=$(square $number) # Command substitution echo \"$value_returned\"

编写一个函数,完成最大公约数的求解,并在shell脚本中调用。 #!/bin/bash

function fun { local m

n=$1 m=$2 while [ $n -ne 0 ] do

if [ $n -le $m ] then

k=$n n=$m m=$k fi

let \"n=n%m\" done

echo \"The greatest common divisor is $m\" }

echo \"Please input the numbers you want for calculation\" read num1 num2

=$(fun $num1 $num2 ) echo \"$\"

5. 请编写一个shell脚本,完成密码的输入与验证,假设已知密码为”secret”。

#!/bin/bash

echo \"Please input the password:\"

read p

if [ $p = secret ] then

echo \"You have enter the system\" else

echo \"Wrong password\" fi

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务