Eg32、while/until/for经典例子 #!/bin/bash ## filename: while-infinite_loops.sh while true; do sleep 5 echo "infinite loops [ hit CTRL+C to stop]" done |
Eg33、while/until/for经典例子 #!/bin/bash ## filename: until-infinite_loops.sh until false; do sleep 5 echo "infinite loops [ hit CTRL+C to stop]" done |
Eg34、while/until/for经典例子 #!/bin/bash ## filename: for-infinite_loops.sh for (( ; ; )); do sleep 5 echo "infinite loops [ hit CTRL+C to stop]" done 具体执行都是一样的: |
Eg35、将循环接管通过管道传递给其他命令(done |) #!/bin/bash ## filename: loop--to_pipe.sh for i in 7 8 9 2 3 4 5 11; do echo $i done | sort -n awk -F':' '$3 >= 500 {print $1}' /etc/passwd | while IFS= read -r person do echo $person done | sort ##该 awk 命令从 /etc/passwd 文件中筛选出 UID 大于等于 500 的行,并仅输出这些行的用户名。 awk 是一个强大的文本分析工具,用于逐行处理输入文件。 -F: 指定了字段分隔符为冒号(:),这是 /etc/passwd 文件中各字段间的分隔符。 '$3 >= 500 {print $1}' 是 awk 的脚本部分:
- $3 >= 500 是条件表达式,检查每一行的第三个字段(即UID)是否大于等于 500。
- {print $1} 是满足条件时执行的动作,打印当前行的第一个字段(即用户名)。
|
Eg36、后台执行循环(done &) #!/bin/bash ## filename: loop--in_background.sh nobody=xh_ry@163.com linux=38742777@qq.com for person in $linux $nobody do #mail -s "Test" $person < "Hello everyone" echo "hi,ih" | mail -s "test loop-in-backgroud" $person done & awk -F':' '$3 >= 500 {print $1}' /etc/passwd | while IFS= read -r person do mail -s "2nd mail test" $person <<-END Hello $person, This message is from $(hostname -f). $USER $(date +%F) END done & 执行后会发送邮件给nobody和linux,注意第二段的脚本需要执行mail -s交互性操作。可以分离输入。 |
Eg37、while实现循环菜单 #!/bin/bash ## filename: what-lang-do-you-like_while.sh while : do echo "====== Scripting Language ======" echo "1) bash" echo "2) perl" echo "3) python" echo "4) ruby" echo "5) (Quit) " read -p "What is your preferred scripting language? " lang case $lang in 1|bash) echo "You selected bash" ;; 2|perl) echo "You selected perl" ;; 3|python) echo "You selected python";; 4|ruby) echo "You selected ruby" ;; 5|quit) break ;; esac done |
Eg38、select实现循环菜单1。 #!/bin/bash ## filename: what-lang-do-you-like_select.sh clear PS3="What is your preferred scripting language? " select s in bash perl python ruby quit do case $s in bash|perl|python|ruby) echo "You selected $s" ;; quit) break ;; *) echo "You selected error , retry …" ;; esac done |
Eg39、select实现循环菜单2。 #!/bin/bash ## filename: what-os-do-you-like_select.sh clear PS3="What is your preferred OS? " IFS='|' os="Linux|Gnu Hurd|FreeBSD|Mac OS X" select s in $os do case $REPLY in 1|2|3|4) echo "You selected $s" ;; *) break ;; esac done |
Eg40、select实现循环菜单3。 #!/bin/bash ## filename: /root/bin/xtop ## filename: what-cmd-do-you-want_select.sh PS3="Select a program you want to execute: " TOPLIST="top htop atop nettop jnettop iftop ftop iotop mytop innotop dnstop apachetop" clear select prog in $TOPLIST quit do [[ $prog == quit ]] && exit apt list --installed $prgo 2>&1 > /dev/null #dpkg -s $prog > /dev/null #rpm -q $prog > /dev/null && $prog || echo " $prog is not installed." done rpm是redhat/rhel下的,dpkg是debian下的检测包安装命令 执行如下: 选择1后, q退出后继续选择3,6,9,13结束。 |
Eg41、for遍历-参数个数-实例 #!/bin/bash ## filename: pp_traverse_1.sh # Usage: pp_traverse_1.sh [arguments] # echo "The name of this script is: `basename $0`" echo "The arguments are: $*" echo "The number of arguments is: $#" for i ; do echo "$i" ; done num=1 for i ; do echo "The ${num}th argument is: $i" ((num++)) done |
Eg42、while实现-参数遍历实例 #!/bin/bash ## filename: pp_traverse_2.sh # This script is to test command line arguments # Usage: pp_traverse_2.sh [arguments] # echo "----- using the first kind of method ---- " num=1 while [ $num -le $# ] do # eval para=\$$num # echo "The ${num}th argument is: $para" echo "The ${num}th argument is: ${!num}" let num=num+1 done echo "----- using the second kind of method --- " for (( num=1 ; num <= $# ; num++)) ; do echo "The ${num}th argument is: ${!num}" done |
Eg43、使用_shift_while遍历的实例 #!/bin/bash ## filename: pp_traverse_shift_while.sh # Usage: pp_traverse_shift_while.sh [arguments] # echo "using while loop to traverse positional parameter" #while [[ "$1" ]] ; do # echo "$1" # shift #done num=1 while [[ "$1" ]] ; do echo "The ${num}th argument is: $1" let num=num+1 shift done |
Eg44、使用_shift_until遍历的实例 #!/bin/bash ## filename: pp_traverse_shift_until.sh # Usage: pp_traverse_shift_until.sh [arguments] # echo "using until loop to traverse positional parameter" #until [ -z "$1" ] ; do # echo "$1" # shift #done num=1 until [ -z "$1" ] do echo "The ${num}th argument is: $1" ((num++)) shift done |
Eg45、使用_shift_for遍历的实例 #!/bin/bash ## filename: pp_traverse_shift_for.sh # Usage: pp_traverse_shift_for.sh [arguments] # echo "using for loop to traverse positional parameter" #for (( ; ; )) ; do # [ -n "$1" ] && echo "$1" || break # shift #done for (( num=1 ; ; num++ )) ; do [ -n "$1" ] && echo "The ${num}th argument is: $1" || break shift done |
Eg46、shift位置参数变量实例-实现HTM重命名为html。 #!/bin/bash ## filename: ren if [ $# -lt 3 ] ; then cat <<_HELP_ FUNCTION: Renames a number of files using sed regular expressions. USAGE: $0 '<regexp>' '<replacement>' <files ...> EXAMPLE: Rename all *.HTM files to *.html: $0 'HTM$' 'html' *.HTM _HELP_ exit 1 fi OLD="$1" ; NEW="$2" ; shift ; shift # $* contains now all the files for file in $*; do if [ -f "$file" ] ; then ##检查当前文件($file)是否存在且为普通文件(非目录、设备文件等) newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"` ##使用 sed 命令将文件名中的OLD变量(即传入的正则表达式)替换为##NEW变量(即替换字符串),并将新文件名赋值给变量newfile。 if [ -f "$newfile" ]; then echo "ERROR: $newfile exists already." else echo "Renaming $file to $newfile." mv "$file" "$newfile" fi ##检查新文件名($newfile)是否已存在。如果存在,输出错误信息;否 则,输出重命名信息,并使用 mv 命令将原文件名($file)重命名为新文件名($newfile)。 fi done |
Eg47、getops使用分析-实例1 #!/bin/bash ## filename : pp_parse_getopts_1.sh while getopts "abc:def:ghi" flag do echo "$flag" $OPTIND $OPTARG done echo "Resetting" OPTIND=1 while getopts "bc:def:ghi" flag do echo "$flag" $OPTIND $OPTARG Done
这是一个使用`getopts`命令处理命令行选项的Bash脚本。 - 使用`getopts`命令解析命令行选项。参数`"abc:def:ghi"`定义了可接受的选项及其特性: - `a`, `b`, `c`: 无参数的选项。 - `d`, `e`, `f`: 需要接一个参数的选项(参数由`:`后跟的字母标识)。 - `g`, `h`, `i`: 同样是无参数的选项。 `getopts`会在循环中逐一处理这些选项及其可能的参数。每次迭代中: - `flag`变量保存当前处理的选项字符(如`a`、`b`、`d`等)。 - `echo "$flag" $OPTIND $OPTARG`打印当前选项字符、当前选项索引(`$OPTIND`)以及选项参数(如果有的话,保存在`$OPTARG`中)。 - 输出消息“Resetting”,表明即将重新开始解析选项。 - 将`OPTIND`(选项索引)重置为1,以便重新从头开始解析选项。 - 第二次使用`getopts`命令解析相同的选项集。由于`OPTIND`已被重置,这次解析将从头开始处理命令行选项,就像第一次从未发生过一样。 该脚本使用`getopts`命令两次解析相同的命令行选项集(`"abc:def:ghi"`)。每次解析过程中,脚本会打印出当前处理的选项字符、选项索引及可能的选项参数。第二次解析之前,脚本重置了`OPTIND`,使得第二次解析如同第一次一样从头开始。 |
|
Eg48、getops使用分析-实例2 linux@LAPTOP-X280:~$ cat 48eg.sh #!/bin/bash ## filename : pp_parse_getopts_1.sh while getopts ":abc:def:ghi" flag do echo "$flag" $OPTIND $OPTARG done echo "Resetting" OPTIND=1 while getopts ":bc:def:ghi" flag do echo "$flag" $OPTIND $OPTARG done |
Eg49、getops使用分析-实例3- #!/bin/bash ## filename : mybackup_getopts.sh while getopts :zc:x:rv opt do case $opt in c) ConfFile=$OPTARG ;; x) ExcludeFile=$OPTARG ;; z) Compress=true ;; r) Recursive=true ;; v) Verbose=true ;; :) echo "$0: Must supply an argument to -$OPTARG." >&2 exit 1 ;; \?) echo "Invalid option -$OPTARG ignored." >&2 ;; esac done shift $((OPTIND-1)) ; echo $0 ; echo "$@" <--undo--> |
Eg50、getops使用分析-实例4- #!/bin/bash ## filename : mybackup_getopts2.sh while getopts :zc:x:rv opt do case $opt in c) if [[ $OPTARG = -* ]]; then ((OPTIND--)) ; continue ; fi ConfFile=$OPTARG ;; x) ExcludeFile=$OPTARG ;; z) Compress=true ;; r) Recursive=true ;; v) Verbose=true ;; :) echo "$0: Must supply an argument to -$OPTARG." >&2 exit 1 ;; \?) echo "Invalid option -$OPTARG ignored." >&2 ;; esac done shift ((OPTIND-1)) ; echo $0 ; echo "$@" <--undo--> |
Eg51、函数实现的backup菜单 #!/bin/bash ## filename: all_in_one_backup_select.sh ### User define Function (UDF) ### sql_bak () { echo "Running mysqldump tool..."; } sync_bak () { echo "Running rsync tool..."; } git_bak () { echo "Running gistore tool..."; } tar_bak () { echo "Running tar tool..."; } ### Main script starts here ### PS3="Please choose a backup tools : " select s in mysqldump rsync gistore tar quit ; do case $REPLY in 1) sql_bak ;; 2) sync_bak ;; 3) git_bak ;; 4) tar_bak ;; 5) exit ;; esac done |
Eg52、函数的局部变量例子 #!/bin/bash ## filename: pp_and_function.sh echo "===Print positional parameters in main :" echo "$0: $*" pp1(){ echo 'f1--Print $* parameters in fun1 :' ; echo "$0: $*" } pp2(){ echo 'f2--Print $* parameters in fun1 :' ; echo "$0: $*" pp1 1st 2nd 3th 4th 5th 6th 7th 8th 9th echo 'f2--Print $* parameters in fun1 :' ; echo "$0: $*" } pp1 1 2 3 4 5 6 7 8 9 echo "===Print positional parameters in main :" echo "$0: $*" pp2 I II III IV V VI VII VIII IX |
Eg53、位置参数函数-比大小 #!/bin/bash ## filename: function_max.sh # User define Function (UDF) usage () { echo "List the MAX of the positive integers in command line. " echo "Usage: `basename $0` <num1> <num2> [ <num3> ... ]" exit } max () { [[ -z $1 || -z $2 ]] && usage largest=0 for i ; do ((i>largest)) && largest=$i ; done } ### Main script starts here ### max "$@" echo "The largest of the numbers is $largest." |
Eg54、函数的返回值调用-实例 #!/bin/bash ## filename: function_max2.sh # User define Function (UDF) max2 () { if [[ -z $1 || -z $2 ]] ; then echo "Need 2 parameters to the function." ; exit fi [ $1 -eq $2 ] && { echo "The two numbers are equal." ; exit ; } (($1>$2)) && return $1 || return $2 } ### Main script starts here ### read -p "Please input two integer numbers : " n1 n2 echo "n1=$n1 , n2=$n2" max2 $n1 $n2 return_val=$? echo "The larger of the two numbers is $return_val." |