LinuxShell脚本编程实例
- 格式:doc
- 大小:48.00 KB
- 文档页数:8
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实验作业参考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脚本实现对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脚本来实现自动化配置。
linux实验三Shell编程实验三:Shell编程一.实验目的巩固所学的Linux下shell编程语言,熟悉Shell脚本。
二.实验内容1.建立一个test目录2.进入此test目录3.新建文件test1,运行下面shell脚本#!/bin/sha = "hello world"echo $a回答此脚本运行结果4.下面两种脚本,哪一个能够输出语句this is the 2nd①num=2echo "this is the $numnd"②num=2echo "this is the ${num}nd"5.若有如下shell脚本注意:空格很重要。
要确保方括号里的空格#!/bin/shif [ "$SHELL" = "/bin/bash" ]; thenecho "your login shell is the bash (bourne again shell)" else echo "your login shell is not bash but $SHELL"fi①请回答此脚本中提到的环境变量②请回答此脚本的功能6.若有如下shell脚本#!/bin/shn=0while read line;dolet "a+=$line"let "n+=1"done < filetest.txtecho $necho $a①请回答此脚本中是否包含循环,若有实现什么操作?②请回答此脚本的功能7.①新建文件test2,运行下面shell脚本#!/bin/bashecho "Your choice?"select var in "a" "b" "c"; dobreakdoneecho $var请回答此脚本运行结果②给出你对下面脚本的理解#!/bin/shecho "What is your favourite OS?"select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do breakdoneecho "You have selected $var"8.阅读下面脚本#!/bin/shhelp(){cat <This is a generic command line parser demo.USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1somefile2HELPexit 0}while [ -n "$1" ]; docase $1 in-h) help;shift 1;; # function help is called-f) opt_f=1;shift 1;; # variable opt_f is set-l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2--) shift;break;; # end of options-*) echo "error: no such option $1. -h for help";exit 1;;*) break;;esacdoneecho "opt_f is $opt_f"echo "opt_l is $opt_l"echo "first arg is $1"echo "2nd arg is $2"注意:shift作用是移除当前参数,若shift 2则移除当前和下一个参数①此shell中case语句试图实现什么功能?②若将shell保存为cmdparser,则执行cmdparser -l hello -f -- -somefile1 somefile2会有什么结果?9.阅读下面shell脚本#!/bin/bashif [ $# -lt 3 ]; thencat<<help< p="">ren -- renames a number of files using sed regular expressionsUSAGE: ren 'regexp' 'replacement' filesEXAMPLE: rename all *.HTM files in *.html:ren 'HTM$' 'html' *.HTMHELPexit 0fiOLD="$1"NEW="$2"# The shift command removes one argument from the list of # command line arguments.shiftshift# $* contains now all the files:for file in $*; doif [ -f "$file" ]; thennewfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`if [ -f "$newfile" ]; thenecho "ERROR: $newfile exists already"elseecho "renaming $file to $newfile "mv "$file" "$newfile"fifidone注意:sed基本上可以看成一个查找替换程序,从标准输入读入文本,并将结果输出到标准输出,sed使用正则表达式进行搜索。
Linux编程_Shell脚本练习题1,编写shell脚本,计算1~100的和。
#! /bin/bashsum=0for i in `seq1100`;dosum=$[$i+$sum]doneecho $sum2,编写shell脚本,输⼊⼀个数字n并计算1~n的和。
要求:如果输⼊的数字⼩于1,则重新输⼊,直到输⼊正确的数字为⽌。
#! /bin/bashread -p "input number:" nsum=0;for((i=0;i<=$n;i++))dosum=`expr $sum + $i`doneecho $sum3,编写shell脚本,批量建⽴⽤户user_00、user_er_99。
要求:所有⽤户同属于users组。
#! /bin/bashgroupadd usersfor i in `seq -w09uesradd -g users user_0$i4done4,编写shell脚本,批量添加⽤户 jsj01-jsj09、jsj10-jsj99。
#! /bin/bashfor((i=1;i<20;i++));doif(i<10);thenjsj="jsj0$i";elsejsj="jsj$i";fiuseradd $jsjdone5,编写shell脚本,要求实现如下功能:当执⾏⼀个程序的时候,这个程序会让使⽤者选择boy或者girl;如果使⽤者输⼊B或者b时,就显⽰:He is a boy;如果使⽤者输⼊G 或者g时,就显⽰:He is a girl;如果是除了B/b/G/g以外的其他字符,就显⽰:I don’t know。
#! /bin/bashecho -n your choice:read choicecase $choice ing)echo"She is a girl.";;G)echo"She is a girl.";;b)echo"He is a boy.";;B)echo"He is a boy.";;*)echo"I don't know.";;esac6,编写shell脚本,实现两个变量之间的加减乘除运算。
1、打印位置变量的个数和位置变量的内容#! /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 $$"2、循环打印“I love linux”3次#!/bin/bashtimes=0until [ "$times" = 3 ];doecho "I love linux."sleep 2times=`expr $times + 1`done3、完成菜单程序的功能:1)列出当前的文件2)更改路径3)编辑文件4)删除文件#!/bin/bash# menu shell script.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 idecho your user id is: $idif (( id == 0 )) # or [ $id -eq 0 ]thenecho "you are superuser."elseecho "you are not superuser."fiShell编程实例一该实例的功能是按照/etc/hosts文件中的条目逐一ping所有的机器。