LinuxShell脚本编程实例
- 格式:doc
- 大小:29.00 KB
- 文档页数:6
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是打印最后一个列。
实验三: 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实验作业参考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例、练习使⽤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编程一、实验目的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系统中,服务是指在后台运行并提供各种功能的应用程序。
对于系统管理员来说,管理服务是非常重要和常见的任务。
为了更高效地管理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`,分别用于启动、停止和重启服务。
实验三 Shell脚本编程实验一、实验目的1.掌握Shell编程的基本方法2.了解Shell脚本的基础知识二、实验要求1.完成一个简单Shell程序的编写和执行过程;2.设计一个Shell程序,显示欢迎界面;3.使用until语句创建一个输入exit退出的Shell程序。
三、实验准备Shell是一个命令语言解释器,它拥有自己内建的Shell命令集,Shell也能被系统中其他应用程序调用。
用户在提示符下输入的命令都由Shell解释后传给Linux核心。
Shell的另一个重要特性是它自身就是一个解释型的程序设计语言。
Shell程序设计语言支持绝大多数在高级语言中能见到的程序元素,如函数、变量、数组和程序控制结构。
Shell 编程语言简单易学,任何在提示符中能键入的命令都能放到一个执行的Shell程序中。
Shell脚本的建立和执行Shell程序可以存放在文件中,这种被Shell解释执行的命令文件称为Shell脚本(Shellscript),也称做Shell文件或者Shell过程。
Shell脚本可以包含任意从键盘输入的UNIX命令。
1)·.Shell脚本的建立建立Shell脚本的方法同建立普通文本文件的方法相同,利用编辑器(如vi)进行程序录入和编辑加工。
例如,要建立一个名为ex1的Shell的脚本,可以在提示符后打入命令:$ vi ex12). 执行Shell脚本的方式执行Shell脚本的方式基本上有三种:(1)输入定向到Shell这种方式是用输入重定向方式让Shell从给定文件中读入命令行并进行相应处理。
其一般形式是:$ sh < 脚本名例如,$ sh < ex1(2)以脚本名作为Shell参数。
其一般形式是:$ sh 脚本名[参数] 例如,$ sh ex2 /usr/mengqc/usr/liuzhy(3)将Shell脚本改为有执行权限的文件,由正文编辑器(如vi)建立的Shell脚本,用户通常是不能直接执行的,需要利用命令chmod将它改为有执行权限。
Shell脚本实现Linux系统的网络配置网络配置是使用Shell脚本自动化的一个重要领域。
通过编写适当的Shell脚本,我们可以在Linux系统上实现自动化的网络配置,提高效率并减少错误。
一. Shell脚本网络配置的基础知识在编写Shell脚本来实现Linux系统的网络配置之前,我们首先需要了解一些基础知识。
这些知识包括IP地址、子网掩码、网关、DNS 等。
这些是网络配置中不可或缺的要素,我们需要在Shell脚本中正确地配置它们。
二. Shell脚本实现IP地址配置IP地址是网络中用于标识设备的唯一地址。
在Shell脚本中,我们可以使用`ifconfig`命令来设置设备的IP地址。
示例如下:```shellifconfig eth0 192.168.1.100 netmask 255.255.255.0 up```上述脚本将eth0网卡配置为IP地址为192.168.1.100,子网掩码为255.255.255.0的状态。
三. Shell脚本实现网关配置网关是用于连接不同网络的设备。
在Shell脚本中,我们可以使用`route`命令来设置设备的网关。
示例如下:```shellroute add default gw 192.168.1.1```上述脚本将默认网关设置为192.168.1.1。
四. Shell脚本实现DNS配置DNS(Domain Name System)是用于将域名转换为IP地址的系统。
在Shell脚本中,我们可以使用`/etc/resolv.conf`文件来配置DNS服务器。
示例如下:```shellecho "nameserver 8.8.8.8" > /etc/resolv.conf```上述脚本将DNS服务器设置为8.8.8.8。
五. Shell脚本实现网络配置的自动化为了进一步简化网络配置的过程,我们可以编写一个Shell脚本来实现自动化配置。
#! /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。