shell脚本编程的例子(55例子)-1

前言

为了提高教学质量,并且能够让童鞋们更好的理解和运用shell脚本以及相关编程,特编写了55个shell例子,目前还在整理过程ing,计划分三期完成。请有需要的同学收藏。后续会申请VIP阅读。……

^.^  …… ^…^

 

实验环境:

WSL2 for unbuntu2204 

编辑器:vi 

shell环境:ubuntu2204默认的bash

539865711c0c4ec49e4d9db1ce40d051.png

一、shell执行方式:

第一种:PATH 环境变量的默认值不包含当前目录,

若脚本文件在当前目录,应使用 ./script-file

使用文本编辑器编辑好, 为脚本文件添加可执行权限

chmod +x script-file

./script-file

第二种:PATH 环境变量的默认值包含 ~/bin 目录,

用户可以将自己的脚本文件存放在 ~/bin 目录,

之后即可直接调用脚本文件名执行脚本了

在子Shell中执行

bash script-file

script-file

在当前Shell中执行

source script-file

.  script-file

 

 

注意调用bash和sh区别:

  • bash:Bourne Again SHell (bash) 是 Bourne shell (sh) 的一个替代品。它最初是为替代原始的 Bourne shell而设计的,并提供了更多的功能和改进。bash 是 GNU 项目的一部分,并且是许多系统上的默认 shell。
  • sh:sh 是 Bourne shell 的原始版本,它是 UNIX 系统上最早的 shell 解释器之一。尽管许多现代系统仍然支持 sh,但它的功能相对有限,与 bash 和其他现代 shell(如 zsh、ksh)相比,缺少许多高级特性。

常用调试法:

Bash [-x] [-n] [-v] scriptName

-x 让用户跟踪脚本的执行,此时 shell 对脚本中每条命令的处理过程为:先执行替换,然后显示,再执行它。shell 显示脚本中的行时,会在行首添加一个加号 “ + ”。

-n 对脚本进行语法检查,但不执行;若存在语法错误提示。

-v 在执行脚本之前,按输入的原样打印脚本中的各行。

使用bash内置命令set使整个或部分脚本处于调试模式:

开启:set  [-x] [-n] [-v]

结束:set  [+x] [+n] [+v]

二、命令执行过程:

 

  • 将命令行分成单个命令词
  • 展开别名
  • 展开大括号中的声明({})
  • 展开颚化声明(~)
  • 命令替换 ( $()或``)
  • 再次把命令行分成命令词
  • 展开文件通配(*、?、[abc]等等)
  • 准备I/0重定向(<、>)
  • 运行命令!

三、具体实例:

一些符号解释:省略,请童鞋门自己备注或者笔记!!

Eg1,read的使用

#!/bin/bash

# This script is to test the usage of read

# Scriptname: ex4read.sh

echo "=== examples for testing read ==="

echo -e "What is your name? \c"

read name

echo "Hello $name"

echo

echo -n "Where do you work? "

read

echo "I guess $REPLY keeps you busy!"

echo

read -p "Enter your job title: "

echo "I thought you might be an $REPLY."

echo

echo "=== End of the script ==="

Bash [-x] ex4read.sh

Eg2.if分支语句的使用

linux@LAPTOP-X280:~$ cat if.sh

#!/bin/bash

## filename: areyouok.sh

 

#set -x ### Turn ON debug mode ###

echo

echo -e "Hello $LOGNAME, \c"

echo    "it's nice talking to you."

echo -n "Your present working directory is: "

pwd # Show the name of present directory

echo

#set +x ### Turn OFF debug mode ###

echo -e "The time is `date +%T`!. \nBye"

echo

 

 

echo "---1st demo about if-YorN---"

echo "Are you OK ?"

read answer

# 在 if 的条件判断部分使用扩展的 test 语句 [[...]]

# 在 [[]] 中可以使用shell的通配符进行条件匹配

if  [[ $answer==[Yy]* || $answer==[Mm]aybe ]]

then  echo "Glad to hear it."

fi

 

echo

echo "---2ed demo about if-UPorDown---"

# if 的条件部分可以使用普通的命令进行测试

# 当命令正确执行($?=0)返回真,否则($?<>0)返回假

myhost=peggy0223

if ping -c1 -w2 $myhost &>/dev/null

then

  echo "$myhost is UP."

else

  echo "$myhost is DOWN."

fi

 

echo

echo "---3rd demo about if-IDcheck---"

## filename:  idcheck.sh

# 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=0

#

id=`id | awk -F'[=(]'  '{print $2}'`   # get user ID

echo "your user id is: $id"

if  (( id == 0 ))    # [ $id -eq 0 ]

then

  echo "you are superuser."

else

  echo "you are not superuser."

fi

echo

 

292164849aed4e0eac2355bf1ec93602.png

 

Eg3.分支语句ifelse的使用

#!/bin/bash

## filename: decide_file_type.sh

# if 语句可以嵌套使用

##实现判断文件类型,如是普通文件查看具有什么权限

 

if [ $# -ne 1 ] && echo "Usage: $0 <filename>" ; then

        exit 1

fi

file=$1

#set -x

 

# Check if the file exists

if [ ! -e "$file" ]; then

  echo "$file does not exist."

  exit 1

fi

 

if [ -d $file ];then

        echo "$file is a directory"

elif [ -f $file ];then

        #if [ -r $file -a -w $file -a -x $file ] ; then

        #if [[ -r $file && -w $file && -x $file ]] ; then

        #       echo "You have (rwx) permissioon on $file."

        #fi

 

        # Check file permissions separately

        read_perm=$(stat -c "%A %u %g" "$file" | cut -c 2)

        write_perm=$(stat -c "%A %u %g" "$file" | cut -c 3)

        exec_perm=$(stat -c "%A %u %g" "$file" | cut -c 4)

 

        if [ "$read_perm" = "r" ]; then

          echo "this file Read permission: yes"

        else

          echo "this file Read permission: no"

        fi

 

        if [ "$write_perm" = "w" ]; then

          echo "this file Write permission: yes"

        else

          echo "this file Write permission: no"

        fi

 

        if [ "$exec_perm" = "x" ]; then

          echo "this file Execute permission: yes"

        else

          echo "this file Execute permission: no"

        fi

else

        echo "$file is neither a file nor a directory."

fi

 

 

Eg4,实现小于12的阶乘:

25668ef2995e436a803b3a74a2d89adf.png

执行结果:

21049a7175f343fbb32a646d831347c4.png

code:

#!/bin/sh -

set -x

if test $# -eq 0

then

        echo "Missing arguments"

else if test $1 -gt 12

 

then

        echo "arument too big!"

        exit

#set +x

else

#set -x

        i=$1

        j=1

        while test $i -ne 0

        do

                j=`expr $j \* $i`

                i=`expr $i - 1`

        done

        echo $j

#set +x

        fi

fi

 

 

 

Eg5shell变量的综合应用实例

code

注意:

变量=赋值,空格的使用;

“”、‘’和`` 的区别使用;

注意wins下编辑复制到linux下的vi需要:set ff=unix回车 ;

建议set -x开启debug模式。

#!/bin/sh -

#This script for variables in shell

set -x

wow="hi,boy"

ygu='YGU-dx1a'

clear

echo "$wow ,My name is beautiful girl from $ygu"

echo Home Directory: $HOME

echo command line here is:

echo $0 $*

echo Before shift operation

echo No. of arguments = $#

echo All the arguments: $*

echo \$0 = $0, \$1 = $1, \$2 = $2

shift

echo After one shift operation

echo No. of arguments: $#

echo All the arguments: $*

echo \$0 = $0, \$1 = $1, \$2 = $2

64904690092640768013a9b7e0889ad1.png

执行结果如下:1 3 5 7 9

8572f39cc6484d5cbd6d06041962ffaf.png

执行另一个结果如下:1 a 3 b 5 c 7 d 9 e

a6830cc0724645669b05b93be45babd0.png

 

Eg6、编写一个程序判断/bin目录下的date文件是否存在

code:

set -x

fname=/bin/date

if (test -f "$fname")then

        echo "exit"

fi

执行结果:

1b77ea160c064225bbcd315d0d4e6df1.png

 

 

Eg7、检查id的脚本

1c403512b4cf4015a4692fa0c248204e.png

 

#!/bin/bash

## filename:  idcheck.sh

# 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=0

#  使用bash执行正常,./执行也ok,sh执行出错!

id=`id | awk -F'[=(]'  '{print $2}'`   # get user ID

echo "your user id is: $id"

if  (( id == 0 ))    # [ $id -eq 0 ]

then

  echo "you are superuser."

else

  echo "you are not superuser."

fi

Eg8、if语句-测试询问年龄

70a0a89595374f2496375aafeb826795.png

 

#!/bin/bash

## filename: ask-age.sh

read  -p "How old are you?  "  age

# 使用 Shell算术运算符(())进行条件测试

if ((age<0||age>120)); then

    echo "Out of range !"

    exit 1

fi

# 使用多分支if语句

if   ((age>=0&&age<13)) ; then   echo "Child !"

elif ((age>=13&&age<20)); then   echo "Callan !"

elif ((age>=20&&age<30)); then   echo "P III !"

elif ((age>=30&&age<40)); then   echo "P IV !"

else   echo "Sorry I asked."

fi

 

Eg9、if语句-useronline

232b46681cdd45888c1e71d3f9914ee0.png

#!/bin/bash

## filename: useronline.sh

# bash 138-if.sh root / linux查看效果

# if 语句可以嵌套使用

if [ $# -eq 1 ] # 或 [[ $#==1 ]] 或(($#==1))

then

  if who|grep $1 >/dev/null

  then echo $1 is active.

  else echo $1 is not active.

  fi

else

  echo "Usage: $0 <username>"

  exit 1

fi

 

Eg10、case语句-what-lang-doulike?

037a81f26e854f3cb5a09efc8f77c6d6.png

#!/bin/bash

## filename: what-lang-do-you-like.sh

echo "What is your preferred scripting language?"

echo "1) bash"

echo "2) perl"

echo "3) python"

echo "4) ruby"

echo "5) I do not know !"

read lang

case $lang in

    1) echo "You selected bash"  ;;

    2) echo "You selected perl"  ;;

    3) echo "You selected python";;

    4) echo "You selected ruby"  ;;

    5) exit

esac

 

Eg11、case语句-yeorno?

da95738e750c467c820831194e00098e.png

#!/bin/bash

## filename: yesorno.sh

echo -n "Do you agree with this? [yes or no]: "

read yn

case $yn in

  [Yy] | [Yy][Ee][Ss] ) echo "Agreed."  ;;

  [Nn] | [N|n][O|o]   )

                        echo "Not agreed."

                        exit 1

                        ;;

   *)                   echo "Invalid input." ;;

esac

Eg12、case语句-“一键备份”

4b1d0ff0b841442389b38e98b01b6280.png

#!/bin/bash

## filename: all_in_one_backup.sh

# A shell script to backup mysql, webserver and files.

# opt=$1

case $1 in

   sql) echo "Running mysql backup using mysqldump tool..." ;;

  sync) echo "Running backup using rsync tool..."           ;;

   git) echo "Running backup using gistore tool..."         ;;

   tar) echo "Running tape backup using tar tool..."        ;;

     *)

        echo "Backup shell script utility"

        echo "Usage: $0 {sql|sync|git|tar}"

        echo "  sql  : Run mySQL backup utility."

        echo "  sync : Run web server backup utility."

        echo "  git  : Run gistore backup utility."

        echo "  tar  : Run tape backup utility."

        ;;

esac

 

Eg13、foreach语句-使用字面字符串列表作为 WordList

983c10d76f5c454cb03b5f9344552b73.png

#!/bin/bash

## filename: for1--constant_as_list.sh

# 使用字面字符串列表作为 WordList

for x in centos ubuntu gentoo opensuse

do   echo "$x" ; done

# 若列表项中包含空格必需使用引号括起来

for x in Linux "Gnu Hurd" FreeBSD "Mac OS X"

do  echo "$x" ; done

for x in ls "df -h" "du -sh"

do

    echo "==$x==" ; eval $x

done

 

Eg14、foreach语句-使用变量作为 WordList

858891bc9f9f482b815abadc0e7578b0.png

#!/bin/bash

## filename: for2--variable_as_list.sh

# 使用变量作为 WordList

i=1; weekdays="Mon Tue Wed Thu Fri"

for day in $weekdays ; do

  echo "Weekday $((i++)) : $day"

done

 

OSList="Linux ‘Gnu Hurd’ FreeBSD ‘Mac OS X’"

for x in $OSList Others ; do

  echo "$x"

done

 

Eg15、foreach语句-使用位置参数变量 $@ 作为 WordList

in $@ 可以省略作为 WordList

9c4dbcf53b7643dbbc952c6c87d0cd46.png

#!/bin/bash

## filename: for3--pp_as_list.sh

# 使用位置参数变量 $@ 作为 WordList, in $@ 可以省略

 

#执行:bash 152-foreach.sh Mon Tue wed Thu Fri sat Sun lundi

i=1

for day ; do

  echo -n "Positional parameter $((i++)): $day "

  case $day in

    [Mm]on|[Tt]ue|[Ww]ed|[Tt]hu|[Ff]ri)

       echo " (weekday)" ;;

    [Ss]at|[Ss]un)

       echo " (WEEKEND)" ;;

    *) echo " (Invalid weekday)" ;;

  esac

done

 

Eg16、foreach语句-使用文件名或目录名列表作为 WordList

5f02426efd1e474bb3d7353088a3b849.png

#!/bin/bash

## filename: for4--filenames_as_list.sh

# 使用文件名或目录名列表作为 WordList

 

# 将当前目录下的所有的大写文件名改为小写文件名

for filename in * ; do

  # 使用命令替换生成小写的文件名,赋予新的变量 fn

  fn=$(echo $fname | tr A-Z a-z)

  # 若新生成的小写文件名与原文件名不同,改为小写的文件名

  if [[ $fname != $fn ]] ; then mv $fname $fn ; fi

  # 上面的 if 语句与下面的命令聚合均等效

  # [[ $fname != $fn ]] && mv $fname $fn

  # [[ $fname == $fn ]] || mv $fname $fn

done

 

for fn in /etc/[abcd]*.conf ; do echo $fn ; done

for fn in /etc/cron.{*ly,d}/* ; do echo $fn ; done

for i in *.zip; do

  j="${i%.zip}"; mkdir "$j" && unzip -d "$j" "$i"

done

 

Eg17、foreach语句-使用命令的执行结果作为 WordList

d17633739d9e4937b8212679382251d6.png

#!/bin/bash

## filename: for5--command_output_as_list.sh

# 使用命令的执行结果作为 WordList

i=1

for username in `awk -F: '{print $1}' /etc/passwd`

do

    echo "Username $((i++)) : $username"

done

 

for line in $(cat files.txt|egrep -v "^$|^#") ; do

    echo "$line"; done

 

for suffix in $(seq 254)

do echo "192.168.0.${suffix}"; done

 

for f in $( ls /var/ ); do echo $f; done

 

Eg18、foreach语句-使用数值范围作为  WordList

0f083798461c40ea8ec559a86e6866e3.png

#!/bin/bash

## filename: for6--range-of-numbers_as_list.sh

# 使用数值范围作为 WordList

 

mynet="192.168.0"

for num in {1..254}

do

  echo "IPAdress $num: $mynet.$num"

done

 

# 使用包含步长(increment)的数值范围作为 WordList

for num in {1..10..2}

do

  echo "Number: $num"

done

 

Eg19、foreach-扫描ip检测keysanformIPS-up-or-down

请谨慎操作,或者修改ip地址范围

#!/bin/bash

## filename: for--ssh-keyscan_from_ips.sh

# for 语句可嵌套

for i in 0 1 2 ; do

  for suffix in {1..254} ; do

    ip=192.168.$i.${suffix}

    if  ping -c1 -w2  $ip &>/dev/null

    then

       ssh-keyscan -t rsa,dsa  $ip \

           >> ~/.ssh/known_hosts

    else

        echo "Host ($ip) is DOWN."

    fi

  done

done

 

Eg20、批量添加50个user

请谨慎操作:

 

#!/bin/bash

## filename: addusers_foreach.sh

# 成批添加50个用户

for x in {1..50}      # 或 $(seq 50)

do

    useradd user${x}

    echo "centos"|passwd --stdin user${x}

    chage -d 0  user${x}

done

 

 

--------------------------------------------------------------分隔符------------------------------------------------------------

第二部分21-31个例子

第三部分为32-55。

请查看我的文章。

 

 

Shell脚本高级编程教程,希望对你有所帮助。 Example 10-23. Using continue N in an actual task: 1 # Albert Reiner gives an example of how to use "continue N": 2 # --------------------------------------------------------- 3 4 # Suppose I have a large number of jobs that need to be run, with 5 #+ any data that is to be treated in files of a given name pattern in a 6 #+ directory. There are several machines that access this directory, and 7 #+ I want to distribute the work over these different boxen. Then I 8 #+ usually nohup something like the following on every box: 9 10 while true 11 do 12 for n in .iso.* 13 do 14 [ "$n" = ".iso.opts" ] && continue 15 beta=${n#.iso.} 16 [ -r .Iso.$beta ] && continue 17 [ -r .lock.$beta ] && sleep 10 && continue 18 lockfile -r0 .lock.$beta || continue 19 echo -n "$beta: " `date` 20 run-isotherm $beta 21 date 22 ls -alF .Iso.$beta 23 [ -r .Iso.$beta ] && rm -f .lock.$beta 24 continue 2 25 done 26 break 27 done 28 29 # The details, in particular the sleep N, are particular to my 30 #+ application, but the general pattern is: 31 32 while true 33 do 34 for job in {pattern} 35 do 36 {job already done or running} && continue 37 {mark job as running, do job, mark job as done} 38 continue 2 39 done 40 break # Or something like `sleep 600' to avoid termination. 41 done 42 43 # This way the script will stop only when there are no more jobs to do 44 #+ (including jobs that were added during runtime). Through the use 45 #+ of appropriate lockfiles it can be run on several machines 46 #+ concurrently without duplication of calculations [which run a couple 47 #+ of hours in my case, so I really want to avoid this]. Also, as search 48 #+ always starts again from the beginning, one can encode priorities in 49 #+ the file names. Of course, one could also do this without `continue 2', 50 #+ but then one would have to actually check whether or not some job 51 #+ was done (so that we should immediately look for the next job) or not 52 #+ (in which case we terminate or sleep for a long time before checking 53 #+ for a new job).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个在高校打杂的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值