转:https://blog.csdn.net/xh_w20?type=blog
转:https://www.jb51.net/article/213879.htm
一、环境与概念:
1、环境
操作系统:Centos 7.l9
编辑器:vi
shell环境:/bin/bash
2、shell执行方式:
./1.sh bash 1.sh
3、调用bash和sh区别:
(1)bash
bash:Bourne Again SHell (bash) 是 Bourne shell (sh) 的一个替代品。它最初是为替代原始的 Bourne shell而设计的,并提供了更多的功能和改进。bash 是 GNU 项目的一部分,并且是许多系统上的默认 shell。
(2)sh
sh:sh 是 Bourne shell 的原始版本,它是 UNIX 系统上最早的 shell 解释器之一。尽管许多现代系统仍然支持 sh,但它的功能相对有限,与 bash 和其他现代 shell(如 zsh、ksh)相比,缺少许多高级特性。
4、常用调试法:
(1)调试语法
Bash [-x] [-n] [-v] scriptName
-x 让用户跟踪脚本的执行,此时 shell 对脚本中每条命令的处理过程为:先执行替换,然后显示,再执行它。shell 显示脚本中的行时,会在行首添加一个加号 “ + ”。 -n 对脚本进行语法检查,但不执行;若存在语法错误提示。 -v 在执行脚本之前,按输入的原样打印脚本中的各行。
(2)调试的开启关闭
使用bash内置命令set使整个或部分脚本处于调试模式:
开启:set [-x] [-n] [-v] 结束:set [+x] [+n] [+v]
5、命令执行过程:
①将命令行分成单个命令词 ②展开别名 ③展开大括号中的声明({}) ④展开颚化声明(~) ⑤命令替换 ( $()或``) ⑥再次把命令行分成命令词 ⑦展开文件通配(*、?、[abc]等等) ⑧准备I/0重定向(<、>) ⑨运行命令!
二、实例
1、read的使用
(1)脚本1-read.sh
vi 1-read.sh
#!/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 ==="
(2)执行脚本
sh 1-read.sh
2、if分支语句的使用
(1)2-if脚本
vi 2-if.sh #!/bin/bash ## filename: if.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 [Y/N/M]?" read answer # 在 if 的条件判断部分使用扩展的 test 语句 [[...]] # 在 [[]] 中可以使用shell的通配符进行条件匹配 if test[ $answer==[Yy]* || $answer==[Mm]aybe ] then echo "Glad to hear it." fi echo echo "---2ed demo about if-UPorDown---" # if 的条件部分可以使用普通的命令进行测试 # 当命令正确执行($?=0)返回真,否则($?<>0)返回假 myhost=localhost 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
(2)执行if.sh
sh if.sh
3、分支语句ifelse的使用
(1)3-ifelse.sh
vi 3-ifelse.sh
#!/bin/bash
## filename:ifelse.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
(2)执行脚本
4、实现小于12的阶乘:
(1)执行结果:
vi 4-12.sh
#!/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
(2)执行脚本
sh 4-12.sh 3
5、shell变量的综合应用实例
【注意:
变量=赋值,空格的使用;
“”、‘’和`` 的区别使用;
注意wins下编辑复制到linux下的vi需要:set ff=unix回车 ;
建议set -x开启debug模式。】
(1)5-zonghe.sh
vi 5-zonghe.sh
#!/bin/sh
#This script for variables in shell
set -x #调试作用
wow="hi,boy"
ygu='China'
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
执行结果如下:1 3 5 7 9 执行另一个结果如下:1 a 3 b 5 c 7 d 9 e
(2)执行脚本
sh 5-zonghe.sh
6、编写一个程序判断/bin目录下的date文件是否存在
(1)脚本6-exist.sh
set -x fname=/bin/date if (test -f "$fname") then echo "The file is exist" else echo "The file is not exist" fi
(2)执行脚本
sh 6-exist.sh
7、检查id的脚本
(1)7-idcheck.sh
vi 7-idcheck.sh
#!/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
(2)执行脚本
sh 7-idcheck.sh
8、if语句-测试询问年龄
(1)8-ask-age.sh
#!/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 don't want to say it anymore." fi
(2)执行脚本
sh 8-ask-age.sh
9、if语句-useronline
(1)
#!/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?
#!/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?
#!/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语句-“一键备份”
#!/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
#!/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
#!/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
#!/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
#!/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
#!/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
#!/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
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/xh_w20/article/details/137963782