linux exercise26

1.Bash脚本条件判断和控制流结构


(1)Bash位置参数和退出状态 条件判断和控制流结构

(2)Bash位置参数
有两种简单的方法可以将用户输入读入bash中的变量。第一个方法是使用read提示用户输入(使用-p选项)并将其直接存储到一个或多个变量:
交互式输入
# read -p 'Enter your first and last name: ' FIRST LAST
另一个方法是使用位置参数来读取传递给脚本的命令行参数或选项输入。各种特殊变量存储传递的选项编号
Bash解析的个别参数或整个原始命令行。
指定的位置参数总数:$#
位置参数自身:$0、$1、$2、$3....
所有位置参数: $@、$*
[root@localhost mnt]# vim test.sh
#!/bin/bash
read -p "please give me a address: " a  ##a在这里是一个变量,指定执行脚本时输入的ip
ping -c1 -w1 $a &> /dev/null && echo $a is up || echo $a is down ##ping命令判断该ip主机网络是否通着
[root@localhost mnt]# sh test.sh
please give me a address: 172.25.254.6

172.25.254.6 is up

(3)退出状态:

linux命令完成时,将返回退出状态。成功完成程序时,将返回0的推出状态。这被bash当作逻辑True值。非零退出状态通常表示发生了错误,并且被bash当作逻辑False值。 

例如:grep的退出状态的含义: 
0 – 在指定的文件中找到了模式 
1 – 在指定的文件中未找到模式 
>1 – 一些其他错误(无法打开文件、错误的搜索表达式等) 
推出状态的值被存储在”?”中,可以使用以下命令查看: 

echo $
这里写图片描述


(4)字符串比较运算符:=、!=
[root@localhost mnt]# [ westos = westos ]; echo $? ##"="表示等于,"!="表示不相等
0
[root@localhost mnt]# [ westos = Westos ]; echo $?
1
[root@localhost mnt]# [ westos != Westos ]; echo $?
0



[root@localhost mnt]# a=1  ##给a赋值1
[root@localhost mnt]# b=1  ##给b赋值1
[root@localhost mnt]# [ "$a" = "$b" ] && echo yes || echo no ##当a等于b时,输出yes,否则输出no
yes
[root@localhost mnt]# [ "$a" != "$b" ] && echo yes || echo no ##当a不等于b时,输出yes,否则输出no
no
[root@localhost mnt]# b=2
[root@localhost mnt]# [ "$a" = "$b" ] && echo yes || echo no
no
[root@localhost mnt]# [ "$a" != "$b" ] && echo yes || echo no
yes
[root@localhost mnt]# [ ! "$a" = "$b" ] && echo yes || echo no ##当a不等于b时,输出yes,否则输出no
yes

(5)test具有替代语法,使用方括号"[]"将表达式括起来,这样更易于阅读。
[root@localhost mnt]# [ -n a ]; echo $? ##该命令效果与test -n "$a" ;echo $?相同,"[]"将表达式括起来
0
[root@localhost mnt]# [ -z a ]; echo $? ##该命令效果与test -z "$a" ;echo $?相同,"[]"将表达式括起来
1
[root@localhost mnt]# [ -n b ]; echo $?
0
[root@localhost mnt]# [ -z b ]; echo $?
1

(6)数字比较运算符:-eq、-ne、-lt、-le、-gt、-ge
-le 小于等于
-lt 小于
-gt 大于
-ge 大于等于
-ne 不等于

(7)文件状态运算符:test -{b|c|e|f|d|r|w|x|s|L} FILE/DIRECTORY
-b 块型
-c 字符型
-e 判断文件是否存在
-f 文件型
-d 目录
-x 可执行
-s 是否为空
-L/-h 软链接
-S 嵌套文件
[root@localhost mnt]# [ -b "/dev/vdb" ] && echo yes || echo no ##-b 判断是否是块,是输出yes
yes         
[root@localhost mnt]# [ -c "/dev/pts/0" ]&& echo yes || echo no ##-c 判断是否为字符型
yes
[root@localhost mnt]# [ -e "/mnt" ]&& echo yes || echo no ##-e 判断是否存在
yes
[root@localhost mnt]# [ -f "/mnt/test.sh" ]&& echo yes || echo no##-f 判断是否是文件型
yes
[root@localhost mnt]# [ -d "/etc" ]&& echo yes || echo no ##-d 判断是否为目录
yes
[root@localhost mnt]# [ -x "/mnt/test.sh" ]&& echo yes || echo no##-x 判断是否可执行
yes
[root@localhost mnt]# touch file
[root@localhost mnt]# [ -s "/mnt/file" ]&& echo yes || echo no ##-s 判断是否不为空
no
[root@localhost mnt]# [ -S "/var/lib/MySQL/mysql.sock" ] && echo yes || echo no ##-S 判断是否为嵌套文件
yes


(8)二进制文件运算符:-ef、-nt、-ot
[ 1 -ef 2 ] 1和2互为硬链接
[ 1 -nt 2 ] 1比2新
[ 1 -ot 2 ] 1比2旧
[root@localhost mnt]# [ /bin/mount -ef /usr/bin/mount ] && echo yes || echo no  
yes      ##/bin/mount 和/usr/bin/mount互为硬链接
[root@localhost mnt]# touch test
[root@localhost mnt]# [ /mnt/file -nt /mnt/test ] && echo yes ||echo no 
no      ##/mnt/file 比 /mnt/test 旧
[root@localhost mnt]# [ /mnt/file -ot /mnt/test ] && echo yes ||echo no
yes      ##/mnt/file 比 /mnt/test 旧
逻辑运算符:-o、-a、!、&&、||
[ a -o b ] ##条件a或者条件b成立
[ a -a b ] ##条件a和条件b都成立
[ ! a ]  ##条件a不成立
[ a ] && 1 || 2 ##当条件a成立时,执行1,否则执行2
[root@localhost mnt]# [ 2 -gt 1 -o 2 -lt 1 ] && echo yes || echo no ##当2大于1成立或者2小于1成立时,输出yes
yes
[root@localhost mnt]# [ 2 -gt 1 -a 2 -lt 1 ] && echo yes || echo no ##当2大于1成立并且2小于1成立时,输出yes
no

2.if语句
if命令检查if后面的命令或列表的退出值。如果第一个命令评估为true/零,则运行then之后的命令列表,直至任一else。如果第一个命令评估为false/非零,则运行else与fi之间的命令列表(反向平写if,标记if块的结束)。
语法:if command; then command; command2; else command3; fi

脚本示例
eg1 实现自动建立文件写入的用户密码设置为westos,如果用户存在则不做任何操作

[root@localhost mnt]# vim create_user.sh
#!/bin/bash      ##如果if后面的条件成立,则执行then后面的命令,否则直接进入else
if
[ -z "$*" ]      ##判断脚本后面的字符是否不存在
then       ##如不存在则执行then后面的命令
        echo "USE: /mnt/create_user /mnt/userfile"
else       ##否则执行else后面的命令
for NUM in $(seq 1 `wc -l $* | cut  -d " " -f 1`)      ##将$1中的行数赋值给NUM
do      NAME=`sed -n ${NUM}p $*`                      ##将$1中的内容一行一行赋给变量NAME
        id $NAME &>/dev/null                                 ##用id命令判断用户是否存在
        if [ "$?" = "0" ]                                                 ##如果$?=0成立即用户存在则输出$NAME is exist
        then echo $NAME is exist
        else `useradd $NAME`                                 ##否则执行建立用户
        `echo westos | passwd --stdin $NAME` &>/dev/null       ##设定密码为westos
        fi
done

fi

[root@localhost mnt]# chmod +x create_user.sh  [root@localhost mnt]# vim userfile user1 user2 user3 [root@localhost mnt]# sh create_user.sh  USE: /mnt/create_user /mnt/userfile [root@localhost mnt]# sh create_user.sh userfile  [root@localhost mnt]# id user1 uid=1001(user1) gid=1001(user1) groups=1001(user1)

eg2 实现自动建立文件写入的用户密码设置为westos,如果用户存在则不做任何操作 [root@localhost mnt]# vim create_user1.sh #!/bin/bash if      [ -z "$1" ] then    echo please give me a userfile elif    [ ! -e "$1" ] then    echo "$1 is not exist" else         for NAME in `cat $1`         do                 USER=`getent passwd $NAME`  ##用getent命令判断用户是否存在                 if      [ -z "$USER" ]                 then    useradd $NAME                         echo westos | passwd --stdin $NAME                 else    echo $NAME is exist                 fi         done fi

[root@localhost mnt]# sh create_user1.sh userfile1 Changing password for user user4. passwd: all authentication tokens updated successfully. Changing password for user user5. passwd: all authentication tokens updated successfully. Changing password for user user6. passwd: all authentication tokens updated successfully.

eg3 脚本控制自动建立删除用户 [root@localhost mnt]# vim ctrl_user.sh #!/bin/bash if       [ "$1" = "create" ]     ##$1表示脚本后第一个字符,当$1=create即表示要建立用户 then       ##如果上述条件成立,则读then包含的命令,如果不成立则进入elif         if      ##当$1=create时要做的动作                 [ -z "$2" ]    ##判断$2是否为空,如果为空则执行then,否则进入elif         then                 echo please give me a userfile  ##$2为空时,执行此命令         elif                 [ ! -e "$2" ]    ##$2不为空时,判断$2是否存在,如果不存在执行then如果存在进入else         then                 echo "$2 is not exist"            else                 for NAME in `cat $2`   ##for,do,done语句建立用户                 do                              USER=`getent passwd $NAME`                 if                         [ -z "$USER" ]                 then                         useradd $NAME                         echo westos | passwd --stdin $NAME                 else                         echo $NAME is exist                 fi                 done         fi elif       ##当$1=delete时要做的动作 [ "$1" = "delete" ] then         if                 [ -z "$2" ]         then                 echo please give me a userfile         elif                 [ ! -e "$2" ]         then                 echo "$2 is not exist"         else                 for NAME in `cat $2`                 do                         USER=`getent passwd $NAME`                 if                         [ ! -z "$USER" ]                 then                         userdel -r $NAME                 else                         echo $NAME is not exist                 fi                 done         fi else      ##当$1,$2既不是create,又不是delete是执行此命令         echo "Useage:ctrl_user.sh <create|delete> <userfile>" fi      ##每一个if语句都要以fi结束

脚本实现 自动回答问题 [root@localhost mnt]# vim answer.exp #!/usr/bin/expect spawn /mnt/ask.sh expect "Who" send "mimi\r" expect "old" send "12\r" expect "class" send "math\r" expect "feel" send "good\r" expect eof [root@localhost mnt]# expect answer.exp  spawn /mnt/ask.sh who are you: mimi How old are you: 12 what's you study: math How do you feel: good mimi is 12's old study math and feel good

答案不为固定时,$argv 0,  $argv 1, $argv 2, $argv 3 表示脚本后面的第1,2,3,4个变量的值  [root@localhost mnt]# vim answer.exp #!/usr/bin/expect set NAME  [ lindex $argv 0 ] set AGE   [ lindex $argv 1 ] set CLASS [ lindex $argv 2 ] set FEEL [ lindex $argv 3 ] spawn /mnt/ask.sh expect "Who" send "$NAME\r" expect "old" send "$AGE\r" expect "class" send "$CLASS\r" expect "feel" send "$FEEL\r" expect eof [root@localhost mnt]# expect answer.exp  mimi 12 math good  ##脚本加变量执行后自动生成答案 spawn /mnt/ask.sh who are you: mimi How old are you: 12 what's you study: math How do you feel: good mimi is 12's old study math and feel good

实现功能 脚本+ip+password自动ssh远程链接  [root@localhost mnt]# vim authssh.exp #!/usr/bin/expect set IP [ lindex $argv 0 ] set PASS [ lindex $argv 1 ] spawn ssh root@$IP expect {         "yes/no" { send "yes\r";exp_continue }         "password:" { send "$PASS\r" } } interact

脚本读主机密码记录文显示主机名 [root@localhost mnt]# vim hostname 172.25.254.6 westos 172.25.254.134 redhat

[root@localhost mnt]# vim check_hostname.sh #!/bin/bash if [ -n "$*" ] then         LINE=`wc -l $* | awk '{print $1}'`         for NUM in `seq 1 $LINE`         do         IP=`sed -n ${NUM}p $* | awk '{print $1}'`         PASS=`sed -n ${NUM}p $* | awk '{print $2}'`         /mnt/autossh.exp $IP $PASS hostname | tail -n 1         done else         echo "Useage:check_host.sh <filename>" fi

shell中的变量分为三类:环境级,用户级,系统级 环境级:重新打开一个shell即时失效

用户级:只能在设置的用户使用,切换则失效 [root@localhost ~]# vim .bash_profile

系统级:整个系统都有效 [root@localhost ~]# vim /etc/profile

shell和脚本使用变量来存储数据 ,有些变量可以连同它们的内容传递给子进程,这些变量我们称之为环境变量。 [root@localhost mnt]# qq=redhat [root@localhost mnt]# echo $qq redhat [root@localhost mnt]# bash [root@localhost mnt]# echo $qq

[root@localhost mnt]# exit exit [root@localhost mnt]# export qq [root@localhost mnt]# bash [root@localhost mnt]# echo $qq redhat [root@localhost mnt]# exit exit

14.使用env命令显示所有环境变量 使用set命令现实所有本地定义的shell变量Bash启动脚本在用户登录的时候,会运行全局变量文件/etc/profile,和用户自定义~/.bash_profile去初始化它们的环境变量。 /etc/profile \_ /etc/profile.d/*.sh ~/.bash_profile \_ ~/.bashrc \_ /etc/bashrc

case语句 :它能够把变量的内容与多个模板进行匹配,再根据成功匹配的模板去决定应该执行哪 
部分代码。 
case .. in 
..) ##条件1 
;; 
..) ##条件2 
;; 
esac ##结束点

例:

#!/bin/bash
case $1 in
start)
systemctl start firewalld
;;
stop)
systemctl stop firewalld
;;
esac

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

使用函数
pathmunge () {
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
}
...
if [ "$EUID" = "0" ]; then
pathmunge /usr/sbin
pathmunge /usr/local/sbin
else
pathmunge /usr/local/sbin after
pathmunge /usr/sbin after
fi





 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值