LinuxShell脚本编程实例

合集下载

Shell 经典实例

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 脚本实例

经典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

Linux 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例、练习使用

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系统服务管理脚本使用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 -

linux-10 shell编程-shellscripts -
Page 2
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

实验三 Shell脚本编程实验

实验三  Shell脚本编程实验

实验三 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脚本实现Linux系统的网络配置

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脚本来实现自动化配置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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所有的机器。

相关文档
最新文档