LinuxShell脚本编程实例
Shell 经典实例

Thizlinux 系统教程 Shell 经典实例----------------Milo经典小shell1 列目录树的shell脚本如下:#!/bin/sh# dtree: Usage: dtree [any directory]dir=${1:-.}(cd $dir; pwd)find $dir -type d -print | sort -f | sed -e "s,^$1,," -e "/^$/d" -e "s,[^/]*/([^/]*)$,`----1," -e "s,[^/]*/,| ,g"2 while中使用read (file是一个文件)cat file | while read linedoecho $lineecho " :: Please input any key(s):c"str4read=""while truedochr4read=`dd if=/dev/tty bs=1 count=1 2>/dev/null`str4read=$str4read$chr4readif [ "$chr4read" = "" ] ;then break; fidoneecho " :: |$str4read|"done3 将多个空格替换为字符sed 's/[ ][ ]*/ /g'如果空格与tab共存时用sed -e 's/[[:space:]][[:space:]]*/ /g' filename4用脚本实现分割文件#!/bin/bashif [ $# -ne 2 ]; thenecho 'Usage: split file size(in bytes)'exitfifile=$1size=$2if [ ! -f $file ]; thenecho "$file doesn't exist"exitfi#TODO: test if $size is a valid integerfilesize=`/bin/ls -l $file | awk '{print $5}'` echo filesize: $filesizelet pieces=$filesize/$sizelet remain=$filesize-$pieces*$sizeif [ $remain -gt 0 ]; thenlet pieces=$pieces+1fiecho pieces: $piecesi=0while [ $i -lt $pieces ];doecho split: $file.$i:dd if=$file of=$file.$i bs=$size count=1 skip=$i let i=$i+1doneecho "#!/bin/bash" > mergeecho "i=0" >> mergeecho "while [ $i -lt $pieces ];" >> mergeecho "do" >> mergeecho " echo merge: $file.$i" >> mergeecho " if [ ! -f $file.$i ]; then" >> mergeecho " echo merge: $file.$i missed" >> mergeecho " rm -f $file.merged" >> mergeecho " exit" >> mergeecho " fi" >> mergeecho " dd if=$file.$i of=$file.merged bs=$size count=1 seek=$i" >> merge echo " let i=$i+1" >> mergeecho "done" >> mergechmod u+x merge'5得到上月未日期,格式为YYYYMMDDget_lastday_of_lastmonth(){yy=`date +%Y`mm=`date +%m-1|bc`[ $mm -lt 1 ] && mm=12;yy=`expr $yy - 1`aaa=`cal $mm $yy`dd=`echo $aaa|awk '{print $NF}'`echo $yy$mm$dd}print $NF的$NF是打印最后一个列。
经典shell 脚本实例

fi
done
#!/bin/bash
if [ $# -le 0 ]
then
echo "Not enough parameters"
exit 1
fi
#string="2 3 4 5 6"
#set string
sum=0
while [ $# -gt 0 ]
do
sum=`expr $sum + $1`
shift
印出该数值,然后再次要求用户输入数值。直到用户输入"end"停止。#!/bin/sh
unset var
while [ "$var" != "end" ]
do
echo -n "please input a number: "
ቤተ መጻሕፍቲ ባይዱ
read var
if [ "$var" = "end" ]
then
break
fi
Linux shell 脚本实例
1. 写一个脚本,利用循环计算 10 的阶乘#!/bin/sh
factorial=1
for a in `seq 1 10`
do
factorial=`expr $factorial \* $a`
done
echo "10! = $factorial"
2. 写一个脚本,执行后,打印一行提示“Please input a number:",要求用户输入数值,然后打
esac done #! /bin/sh a=10 b=20 c=30 value1=`expr $a + $b + $c` echo "The value of value1 is $value1" value2=`expr $c / $b` echo "The value of value2 is $value2" value3=`expr $c * $b` echo "The value of value3 is $value3" value4=`expr $a + $c / $b` echo "The value of value4 is $value4" var4=`expr $value4 - $value2` echo $var4
实验指导书--实验03 Linux Shell编程

实验三: Linux Shell编程
实验学时: 2
实验类型: 设计
实验要求: 必修
一、实验目的
通过本实验的学习, 使学生掌握Shell编程的基本方法。
二、实验内容
实验内容: Linux Shell实现题目所要求的功能。
三、实验原理、方法和手段
无
四、实验组织运行要求
以学生自主训练为主的开放模式组织教学
五、实验条件
PC机
六、实验步骤
1.编写一个Shell脚本, 完成以下功能:
1)显示文字“Waiting for a while….”
Vi helloworld
#!/bin/bash
Echo “Waiting for a while….”
2)显示当前目录下面扩展名为”.h”的文件和目录, 并输出重定向到/home/file.txt文件
Find .h
Find .h >>/home/file.txt
提示: 显示文字可使用echo命令, 搜索文件可使用find命令
2.编写一个Shell脚本, 完成以下功能
计算8以内(含8)不是3的整数倍的数字的和
3.编写一个Shell脚本, 在当前目录创建5个目录, 目录的命名形式分别为: dir-1, dir-2, …., dir-5
七、思考题
比较C语言和Shell编程的一些异同点。
八、实验报告
实验预习: 学习shell编程的基本方法
实验记录: 记录解决问题所用的代码和运行结果
实验报告: 提交代码和运行结果
九、其它说明。
Linux shell编程实验作业(含答案)

Linux shell实验作业参考1.编写一个Shell脚本,实现输入一个数字,输出该数字的阶乘。
思路:使用for循环,从1到输入的数字进行累乘,最终输出结果。
#!/bin/bashecho "请输入一个数字:"read numfact=1for ((i=1;i<=$num;i++))dofact=$(($fact*$i))doneecho "阶乘为:$fact"2. 编写一个Shell脚本,实现输入一个目录,输出该目录下所有文件名和文件大小。
#!/bin/bash# 获取目录路径read -p "请输入目录路径:" dir_path# 判断目录是否存在if [ ! -d "$dir_path" ]; thenecho "目录不存在!"exit 1fi# 遍历目录下所有文件for file in "$dir_path"/*do# 判断是否是文件if [ -f "$file" ]; then# 获取文件名和大小file_name=$(basename "$file")file_size=$(du -h "$file" | awk '{print $1}')echo "$file_name : $file_size"fidone使用方法:➢将以上代码保存为一个.sh文件,例如:`list_files.sh`➢给该文件添加执行权限:`chmod +x list_files.sh`➢在终端中运行该脚本:`./list_files.sh`,然后输入目录路径即可。
3. 编写一个Shell脚本,实现输入一个字符串,输出该字符串中所有大写字母的个数。
脚本的基本思路是遍历输入的字符串,对于每个字符,判断是否为大写字母,如果是则计数器加一。
shell脚本100例、练习使用

shell脚本100例、练习使⽤1、编写hello world脚本#!/bin/bashecho"hello world"2、通过位置变量创建linux系统账户和密码#!/bin/bash#$1是执⾏脚本第⼀个参数 $2是执⾏脚本第⼆个参数useradd "$1"echo"$2" | passwd --stdin "$1"#测试脚本[root@template-host sh1]# sh2.sh aaa 123Changing password for user aaa.passwd: all authentication tokens updated successfully.#测试登录[root@template-host sh1]# su - aaa[aaa@template-host ~]$3、每周五使⽤tar命令备份 /var/log下的所有⽇志⽂件#!/bin/bashtar -czPf log-`date +%y%m%d`.tar.gz /var/log #加P是因为如果不加会出现错误:tar: Removing leading `/' from member names date和+之间注意有空格。
修改系统参数[root@template-host sh1]# crontab -e00 03 * * 5 /data/sh1/3.sh4、⼀键部署LNMP(RPM包版本)#!/bin/bash#此脚本需要提前配置yum源,否则⽆法配置成功。
本脚本使⽤于7.4yum -y install httpdyum -y install mariadb mariadb-devel mariadb-serveryum -y install php php-mysqlsystemctl start httpd mariadb #启动httpd、mariadbsystemctl enable httpd mariadb #加⼊开机⾃启动systemctl status httpd mariadb #查看是否成功5、实时监控本机硬盘内存剩余空间,剩余内存空间⼩于500M,根分区剩余空间⼩于1000M时,发送警报信息到命令⾏#!bin/bash#提取分区剩余空间单位:kbdisk_size=$(df / | awk'/\//{print $4}')#提取内存空间单位Mmem_size=$(free -m | awk'/Mem/{print $4}')while :doif [ $disk_size -le 512000 -o $mem_size -le 1024 ];thenecho"警报:资源不⾜"sleep5fidone6、随机⽣成⼀个100以内的随机数,提⽰⽤户猜数字,提⽰⽤户猜⼤了、猜⼩了、猜对了,直⾄⽤户猜对,脚本结束。
linux操作系统shell编程

实验五Linux的shell编程一、实验目的1.了解常用shell的编程特点,掌握shell程序设计的基础知识。
2.认识和理解shell程序流程控制、shell程序的运行方式、shell程序的调试方法。
3.基本掌握编写shell程序的步骤、方法和技巧。
二、实验环境Linux软件和计算机三、实验内容或步骤实验准备知识为书上5.3,5.4,5.5以及第23章内容,p73~84,p374-394。
1、shell脚本的建立同建立普通文本文件的方式相同,可利用编辑器vi或cat命令,进行程序录入和编辑加工。
由三条简单命令组成的Shell程序,文件名为prog。
ls –lcalwho2、shell脚本的执行(通常用三种方式)1)、输入定向的执行方式sh < 脚本名如:sh < prog2)、以脚本名作为Shell参数的执行方式sh 脚本名[参数] 如:sh prog3)、改执行权限后直接执行方式如:# chmod a+x prog# ./prog3、Shell变量:1)、可写的环境变量$ echo $PS1$ PS1=“[\u@@@wdg-Linux-9]”2)、位置参数:在命令行传递给shell脚本的参数。
(1)位置参数及引用可以编写一个shell脚本,当从命令行或者从其他shell脚本中调用它的时候,这个脚本接收若干参数。
这些选项是通过Linux作为位置参数(positional parameter)提供给shell程序的。
在shell脚本中应有变量,接收实参,这类变量的名称很特别,分别是1,2,3,…,这类变量称为位置变量。
位置参数1存放在位置变量1中,位置参数2存放位置变量2中,……,在程序中可以使用$1,$2,……来访问。
下述是一个shell程序的mypgm1,只带了一个参数(名字),并在屏幕上显示这个名字:#Name display program1if [ $# -eq 0 ]thenecho“Name not provided”elseecho”Your name is $1”fi在pdksh和bash中,如果执行mypgm1如下:#.mypgm1将得到输出:Name not provided但是,如果执行mypgm1如下:#.mypgm1sanjia则得到如下的输出:Your name is sanjia(2)用set命令为位置参数赋值在shell程序中可以利用set命令为位置参数赋值或重新赋值。
Linux系统服务管理脚本使用Shell脚本实现对Linux系统服务的启动停止和重启操作

Linux系统服务管理脚本使用Shell脚本实现对Linux系统服务的启动停止和重启操作在Linux系统中,服务是指在后台运行并提供各种功能的应用程序。
对于系统管理员来说,管理服务是非常重要和常见的任务。
为了更高效地管理Linux系统服务,可以使用Shell脚本实现对服务的启动、停止和重启操作。
本文将介绍如何使用Shell脚本来管理Linux系统服务。
一、编写Shell脚本首先,我们需要创建一个Shell脚本文件,例如名为“service_manage.sh”。
使用任何一个文本编辑器,打开一个新的文件,并输入以下内容:```shell#!/bin/bashfunction start_service {sudo systemctl start $1}function stop_service {sudo systemctl stop $1}function restart_service {sudo systemctl restart $1}echo "欢迎使用Linux系统服务管理脚本" echo "请输入您想要执行的操作:"echo "1. 启动服务"echo "2. 停止服务"echo "3. 重启服务"read choicecase $choice in1)echo "请输入要启动的服务名:"read service_namestart_service $service_name;;2)echo "请输入要停止的服务名:"read service_namestop_service $service_name;;echo "请输入要重启的服务名:"read service_namerestart_service $service_name;;*)echo "无效的选择";;esac```上述脚本定义了三个函数:`start_service`、`stop_service`和`restart_service`,分别用于启动、停止和重启服务。
linux-10 shell编程-shellscripts -

Shell Scripts
Shell Scripts的优与劣
能够实现系统自动化管理 简单入侵检测 进行较为复杂的数据处理 程序可读性强,具有UNIX LIKE系统通用性 指令执行速度欠佳
Page 3
Shell Scripts
shell scripts撰写注意事项:
指令的执行是从上而下,从左而右 指令与参数间多个空白会被忽略 如果读取到enter符号,会开始执行该行或该串命令 如果一行内容太多,可使用“\enter”来延伸至下一行 “#”作为注释
“”可保留特殊字符的原本特性 ‘’内特殊字符仅为纯文本 可用转义字符’/’将特殊符号变为纯文本
Page 12
Shell Scripts
试一试:
以单引号为变量var赋值:var=‘lang is $LANG’,查看var的值, 再以双引号赋值变量var=“lang is $LANG”,查看var。变量值是 否相同?说明了什么?如果在双引号中以“\”转义特殊字符$, 结果又有什么不同?(查看变量:echo $变量)
Shell Scripts
练习二
使用if…then…elif…then…else..fi等语句,编写脚本程序实现以下功 能:输入学号,程序给出学生姓名,至少能够查询三名同学姓名, 如查询学号不在程序记录范围内,显示“no record!”
Page 32
Shell Scripts
case…esac 多层次条件判断
更简单的条件判断test(21.2.6)
文件测试;字符串比较;数字比较;复合表达式
Page 23
Shell Scripts
Page 24
Shell Scripts
Page 25
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#! /bin/shecho "Current command is $0"echo "The first parameter is $1"echo "The second parameter is $2"echo "The third parameter is $3"echo "Total of parameters if $#"echo "Current PID is $$"#!/bin/bashtimes=0until [ "$times" = 3 ];doecho "I love linux."sleep 2times=`expr $times + 1`done#!/bin/bash# menu shell script. samli 2004.4.19 untilecho "List Directory..........1"echo "Change Directory........2"echo "Edit File...............3"echo "Remove File.............4"echo "Exit Menu...............5"read choicetest $choice = 5docase $choice in1) ls;;2) echo "enter target directory:" read dircd $dir;;3) echo "enter file name:"read filevi $file;;4) echo "enter file name:"read filerm $file;;5) echo "Goodbye";;*) echo "illegal option, please input again." esacdone#! /bin/shvar1="abcd efg"echo $var1var2=1234echo "The value of var2 is $var2"echo $HOMEecho $PATHecho $PWD#! /bin/shnum=0while [ $num -le 10 ]donum=`expr $num + 1`if [ $num -eq 5 ]thencontinuefisquare=`expr $num \* $num`echo $squaredone#!/bin/bash# Gnu bash versions 2.x# The Party Program--Invitations to friends from the# "guest" fileguestfile=./guests # ~/shell/guestsif [[ ! -e "$guestfile" ]]thenprintf "${guestfile##*/} non-existent"exit 1fiexport PLACE="Sarotini's"(( Time=$(date +%H) + 1 ))set cheese crackers shrimp drinks "hot dogs" sandwichesfor person in $(cat $guestfile)doif [[ $person = root ]]thencontinueelse# Start of here documentmail -v -s "Party" $personHi ${person}! Please join me at $PLACE for a party!Meet me at $Time o'clock.I'll bring the ice cream. Would you please bring $1and anything else you would like to eat? Let me knowif you can't make it.Hope to see you soon.Your pal,ellie@$(hostname)FINISshiftif (( $# == 0 ))thenset cheese crackers shrimp drinks "hot dogs" sandwiches fifidoneprintf "Bye..."#!/bin/sh# Standard AT&T Bourne Shell# The Party Program--Invitations to friends from the# "guest" fileguestfile=./guests # /home/ellie/shell/guestsif [ ! -f "$guestfile" ]thenecho "慴asename $guestfile?non-existent"exit 1fiPLACE="Sarotini's"export PLACETime=`date +%H`Time=`expr $Time + 1`set cheese crackers shrimp drinks "hot dogs" sandwichesfor person in $(cat $guestfile)doif [ $person = root ]]thencontinueelse# Start of here documentmail -v -s "Party" $personHi $person! Please join me at $PLACE for a party!Meet me at $Time o'clock.I'll bring the ice cream. Would you please bring $1and anything else you would like to eat? Let me knowif you can't make it.Hope to see you soon.Your pal,ellie@`hostname`FINISshiftif [ $# -eq 0 ]thenset cheese crackers shrimp drinks "hot dogs" sandwiches fifidoneecho "Bye..."#!/bin/sh# Scriptname: args# Script to test command line argumentsecho The name of this script is $0.echo The arguments are $*.echo The first argument is $1.echo The second argument is $2.echo The number of arguments is $#.oldargs=$*set Jake Nicky Scott # reset the positional parameters echo All the positional parameters are $*.echo The number of postional parameters is $#.echo "Good~Vbye for now, $1 "set $(date) # reset the positional parametersecho The date is $2 $3, $6.echo "The value of \$oldargs is $oldargs."set $oldargsecho $1 $2 $3# Name: bigfiles# Purpose: Use the find command to find any files in the root# partition that have not been modified within the past n (any# number within 30 days) days and are larger than 20 blocks# (512 byte blocks)if (( $# != 2 )) # or [ $# -ne 2 ]thenecho "Usage: $0 mdays size " 1>&2exit 1fiif (( $1 0 || $1 > 30 )) # or [ $1 -lt 0 -o $1 -gt 30 ] thenecho "mdays is out of range"exit 2fiif (( $2 # or [ $2 -le 20 ]thenecho "size is out of range"exit 3fifind / -xdev -mtime $1 -size +$2#!/bin/bash# Scriptname: checker# Script to demonstrate the use of special variable# modifiers and argumentsname=${1:?"requires an argument" }echo Hello $name#!/bin/bash# This is the first Bash shell program of the day.# Scriptname: greetings# Written by: Barbara Bashfulecho "Hello $LOGNAME, it's nice talking to you."echo "Your present working directory is `pwd`."echo "You are working on a machine called `uname -n`." echo "Here is a list of your files."ls # list files in the present working directoryecho "Bye for now $LOGNAME. The time is `date +%T`!"#!/bin/bash# Scriptname: greetings2echo "This script is called $0."echo "$0 $1 and $2"echo "The number of positional parameters is $#"#!/bin/bash# Scriptname: idcheck# purpose:check user id to see if user is root.# Only root has a uid of 0.# Format for id output:uid=9496(ellie) gid=40 groups=40# root's uid=0id=`id | gawk -F'[=(]' '{print $2}'` # get user id echo your user id is: $idif (( id == 0 )) # or [ $id -eq 0 ]thenecho "you are superuser."elseecho "you are not superuser."fi。