L7.1 linux shell 条件判断与循环语句

bash脚本条件判断语句详细使用

条件判断的使用方法及其相关示例;

本文对bash中test语句,if判断语句(单分支,多分支)case语句详细说明,如下

条件测试:test

作用:Shell中的test命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。

test使用语法

test EXPRESSION

也可以使用 :[ EXPRESSION ];[[ EXPRESSION ]]

整数测试:

隐含着做数值大小比较,所以不要给变量引用加引用;

$A -gt $B:是否大于;是则为“真”,否则为“假”;

$A -ge $B: 是否大于等于;

$A -lt $B:是否小于;

$A -le $B: 是否小于等于;

$A -eq $B: 是否等于;

$A -ne $B:是否不等于;

示例:整数判断,判断$A,$B的值,是则为“真”(0),否则为“假”(非零);

[[email protected] ~]# cat test.sh 
#!/bin/bash
declare -i A=5
declare -i B=7
echo "$A=5"
echo "$B=7"
echo "以下判断$A,$B的值,是则为“真”(0),否则为“假”(非零);"

echo "$A -gt $B:是否大于;"
test $A -gt $B; echo $?

echo "$A -ge $B: 是否大于等于;"
test $A -ge $B;echo $?

echo "$A -lt $B:是否小于;"
test $A -lt $B;echo $?

echo "$A -le $B: 是否小于等于;"
[ $A -le $B ] ;echo $?

echo "$A -eq $B: 是否等于;"
[ $A -eq $B ];echo $?

echo "$A -ne $B:是否不等于;"
[ $A -ne $B ];echo $?

[[email protected] ~]# ./test.sh 
5=5
7=7
以下判断5,7的值,是则为“真”(0),否则为“假”(非零);
5 -gt 7:是否大于;
1
5 -ge 7: 是否大于等于;
1
5 -lt 7:是否小于;
0
5 -le 7: 是否小于等于;
0
5 -eq 7: 是否等于;
1
5 -ne 7:是否不等于;
0

字符串测试:

ASCII数值越大,字符比较时其值越大;

"$A" > "$B":是否大于;

"$A" < "$B":是否小于;

"$A" == "$B":是否等于;

"$A" != "$B":是否不等于;

-z "$A":是否为空;空则为“真”,否则为“假”

-n "$A":是否不空;不空则“真”,空则为“假”

注意:应该使用[[ EXPRESSION ]]

示例:字符串测试,测试$A与$B

[[email protected] ~]# cat test01.sh 
#!/bin/bash
A=hello
B=world
echo "A is hello"
echo "B is world"
echo "测试字符串$A,$B,是则为“真”(0),否则为“假”(非零);"

echo ""$A" > "$B":是否大于;"
[[ "$A" > "$B" ]];echo $?

echo ""$A" < "$B":是否小于;"
[[ "$A" < "$B" ]];echo $?

echo ""$A" == "$B":是否等于;"
[[ "$A" == "$B" ]];echo $?

echo ""$A" != "$B":是否不等于;"
[[ "$A" != "$B" ]];echo $?

echo "-z "$A":是否为空;空则为“真”,否则为“假”"
[[ -z "$A" ]];echo $?

echo "-n "$A":是否不空;不空则“真”,空则为“假”"
[[ -n "$A" ]];echo $?

[[email protected] ~]# ./test01.sh   
A is hello
B is world
测试字符串hello,world,是则为“真”(0),否则为“假”(非零);
hello > world:是否大于;
1
hello < world:是否小于;
0
hello == world:是否等于;
1
hello != world:是否不等于;
0
-z hello:是否为空;空则为“真”,否则为“假”
1
-n hello:是否不空;不空则“真”,空则为“假”
0

文件测试:

测试文件的存在性以及属性;

-e $file: 是否存在;存在则为“真”,否则为“假”;

-a $file: 同上;

-f $file:文件是否存在且为普通文件;

-d $file:文件是否存在且为目录;

-h $file:是否存在且为符号链接文件;

-L $file: 同上

-b $file:是否存在且为块设备文件;

-c $file:是否存在且为字符设备文件;

-S $file:是否存在且为套接字文件;

-p $file: 是否存在且为管道文件;

-r $file: 当前用户对文件是否拥有读权限;

-w $file:当前用户对文件是否拥有写权限;

-x $file:当前用户对文件是否拥有执行权限;

-u $file:文件是否拥有SUID权限;

-g $file:文件是否拥有SGID权限;

-k $file:文件是否拥有sticky权限;

-O $file: 当前用户是否为指定文件的属主;

-G $file: 当前用户是否为指定文件的属组;

双目操作符:

$file1 -nt $file2: file1是否新于file2, file1的最近一次的修改时间戳是否晚于file2

的;

$file1 -ot $file2: file1是否旧于file2, file1的最近一次的修改时间戳是否早于file2

的;

$file1 -ef $file2:file1与file2是否指向了同一个inode;测试二者是否为同一个文件的硬链接;

示例:常用选项:-e -f -d;-w -x;-u;-nt -ot;

#-e 是否存在,可以是目录,文件等
[[email protected] ~]# test -e /dir            #是否存在(目录)
[[email protected] ~]# echo $?
0
[[email protected] ~]# touch /dir/file1
[[email protected] ~]# test -e /dir/file1     #是否存在(文件)
[[email protected] ~]# echo $?
0
[[email protected] ~]# rm -f /dir/file1 
[[email protected] ~]# test -e /dir/file1 
[[email protected] ~]# echo $?            
1                                          #删除后没有file1文件,返回结果为1

#-f,文件是否存在且为普通文件;针对文件
[[email protected] ~]# touch /dir/file1
[[email protected] ~]# test -f /dir/file1  
[[email protected] ~]# echo $?
0
[[email protected] ~]# test -f /dir/            #测试dir为目录,虽然存在但是不是普通文件,返回结果为1
[[email protected] ~]# echo $?
1

#-d,文件是否存在且为目录;针对目录drwxr-xr-x 第一个d
[[email protected] ~]# test -d /dir
[[email protected] ~]# echo $?
0
[[email protected] ~]# test -d /dir/file1        #测试file1为文件,虽然存在但是不是目录,返回结果为1 
[[email protected] ~]# echo $?
1

#-w,当前用户对文件是否拥有写权限;-x,当前用户对文件是否拥有执行权限;
test -w /dir/file1
test -x /dir/file1

#-u,文件是否拥有SUID权限;
[[email protected] ~]# test -u /dir/file1
[[email protected] ~]# echo $?
1
[[email protected] ~]# chmod u+s /dir/file1 
[[email protected] ~]# test -u /dir/file1   
[[email protected] ~]# echo $?              
0

#-nt,file1是否新于file2,判断基于最近一次的修改时间戳
#-ot,file1是否旧于file2,判断基于最近一次的修改时间戳
[[email protected] ~]# touch file1 && date +%M%S
0133
[[email protected] ~]# touch file2 && date +%M%S 
0139
[[email protected] ~]# test  file1 -nt file2    #file1是否新于file2(否)
[[email protected] ~]# echo $?
1
[[email protected] ~]# test  file2 -nt file1      #file2是否新于file1(是)
[[email protected] ~]# echo $?
0
[[email protected] ~]# echo "hello world">file1       #修改file1
[[email protected] ~]# cat file1 
hello world
[[email protected] ~]# test  file1 -nt file2        #file1因为修改了,所以新于file2了 
[[email protected] ~]# echo $?
0

特殊设备:

/dev/null: 空,bit buckets,吞下所有数据,并直接丢弃;

/dev/zero:吐出一堆0;

示例:

#/dev/null
echo "hello world">/dev/null                #标准输出重定向到/dev/null,无任何显示内容
[[email protected] ~]# error output
bash: error: command not found...
[[email protected] ~]# error input &>/dev/null   #标准输出和标准错误输出都重定向到/dev/null,无任何显示内容
[[email protected] dir]# ls test.sh test1.sh 
ls: cannot access test1.sh: No such file or directory
test.sh
[[email protected] dir]#  ls test.sh test1.sh >/dev/null 2>&1      #将错误输出2 绑定给 正确输出1,然后将正确输出发送给/dev/null设备,无任何内容显示

#/dev/zero  常用方法,制作一个100M大文件
[[email protected] dir]# dd if=/dev/zero of=bigfile bs=M count=100
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 1.75084 s, 59.9 MB/s
[[email protected] dir]# du -h bigfile 
100M    bigfile

bash之条件判断(if语句)

if 语句通过关系运算符判断表达式的真假来决定执行哪个分支,有单分支和多分支if语句,下面详细介绍

单分支if语句

bash之条件判断:格式

if/then, case

if CONDITION; then

if-true-分支

fi

if CONDITION; then

if-true-分支

else

if-false-分支

fi

! CONDITION: 取反(条件取反)

示例:

#如果某路径不存在,则将其创建为目录;否则显示其存在,并显示内容类型;
[[email protected] dir]# cat test.sh    
#!/bin/bash
dirname="/dir/dir01"
if [ -e $dirname ]
then
    echo "$dirname exists."
    file $dirname
else
     mkdir -p $dirname
fi
[[email protected] dir]# ./test.sh    #目录不存在,所以创建了目录dir01
[[email protected] dir]# ls
dir01  test.sh
[[email protected] dir]# ./test.sh #目录以及存在,如下提示
/dir/dir01 exists.
/dir/dir01: directory

#!CONDITION:取反
[[email protected] dir]# if [ ! -z $test ];then echo "$test";else echo ‘$test is zero‘;fi
hello

if语句使用脚本参数(位置参数变量),shift,read命令:

位置参数变量:$1, $2, ...

# ./script.sh /etc/fstab /etc/grub2.cfg

$0        $1       $2

特殊变量:

$?: 命令的状态结果;

$#: 传递给脚本或函数的参数的个数;

$*和[email protected]: 引用传递给脚本或函数的参数列表;

shift [n]:轮替:shift命令会将之前的(左边的)参数删除,用右边的参数替换其位置。参      数表示替换几个(向左移几位)。shift不指定参数默认为1。

与用户交互:

read命令:

read [options] VAR...

-p "PROMPT":提示信息

-t timeout :等待时间

示例:参数位置与shift轮替

例子表示,因为shift将A2,A3依次往左移一位,所以echo$1,$1位置的A1分别被A2,A3逐次替换,最后的$*显示全部参数,因为之前的A1被A2替换,A2被A3所替换,所以最后的$*只剩下A3了.

[[email protected] dir]# cat shift.sh 
#!/bin/bash
#
echo $*
echo $1
shift
echo $1
shift
echo $1
echo $*
[[email protected] dir]# ./shift.sh A1 A2 A3
A1 A2 A3
A1
A2
A3
A3                #$*的值

示例:使用read读入参数变量username为用户名,添加一个用户,如果存在,提示用户存在,不存在则添加用户,等待时间为10秒,等待超时未输入参数变量username,添加指定用户myuser

[[email protected] dir]# cat adduser.sh 
#!/bin/bash
read -p "Plz enter a username: " -t 10 username   #提示输入参数变量,等待为10s
if [ -z "$username" ]
then
     username="myuser"
fi
if id $username &> /dev/null;
then
    echo "$username exists."
else
    useradd $username
fi
[[email protected] dir]# ./adduser.sh 
Plz enter a username: root
root exists.
[[email protected] dir]# ./adduser.sh 
Plz enter a username: user001
[[email protected] dir]# id user001
uid=1006(user001) gid=1006(user001) groups=1006(user001)

命令引用:

`COMMAND`, $(COMMAND)

引用命令的执行结果;

示例:

[[email protected] dir]# ls `which cat`
/usr/bin/cat
[[email protected] dir]# lines=$(wc -l /etc/fstab | cut -d‘ ‘ -f1)
[[email protected] dir]# echo $lines
12
#统计指定文件行数
[[email protected] dir]# cat lines.sh 
#!/bin/bash
#
if [ -f $1 ]
then
    lines=$(wc -l $1 | cut -d‘ ‘ -f1)
    echo "$1 has $lines lines."
else
    echo "$1 not exists or not a file."
fi
[[email protected] dir]# ./lines.sh /etc/passwd
/etc/passwd has 46 lines.

双分支if语句:

if CONDITION; then

if-true-分支

else

if-false-分支

fi

多分支if语句:

if CONDITION1; then

if-CONDITION1-true-分支

elif CONDTION2; then

if-CONDITIO2-true-分支

...

else

if-ALL-false-分支

fi

示例:多分支,通过脚本参数传递一个文件路径给脚本,判断其类型;

#!/bin/bash
#
if [ $# -lt 1 ]; then
     echo "Usage: $0 <path>"
     exit 1
fi
if [ -f $1 ]; then
    echo "Rgular file."
elif [ -d $1 ]; then
echo "Directory."
elif [ -h $1 ]; then
echo "Symbolic link."
elif [ -b $1 ]; then
echo "Block special."
elif [ -c $1 ]; then
echo "Charactoer special."
elif [ -S $1 ]; then
echo "Socket file."
else
echo "file not exist or unknown type."
fi
[[email protected] dir]# ./if.sh 
Usage: ./if.sh <path>
[[email protected] dir]# ./if.sh /etc/passwd
Rgular file.
[[email protected] dir]# ./if.sh /etc/sysconfig
Directory.

case语句

简洁版多分支if语句;

使用场景:判断某变量的值是否为多种情形中的一种时使用;

语法:

case $VARIABLE in

PATTERN1)

分支1

;;

PATTERN2)

分支2

;;

PATTERN3)

分支3

;;

...

*)

分支n

;;

esac

PATTERN可使用glob模式的通配符:

*: 任意长度的任意字符;

?: 任意单个字符;

[]: 指定范围内的任意单个字符;

a|b: 多选1;

示例:提示键入任意一个字符;判断其类型;

#!/bin/bash
#
read -p "Plz enter a character: " char
case $char in
[a-z])
    echo "A character."
    ;;
[0-9])
    echo "A digit."
    ;;
*)
    echo "A special character."
    ;;
esac
[[email protected] dir]# ./case.sh 
Plz enter a character: test
A special character.
[[email protected] dir]# ./case.sh 
Plz enter a character: 12
A special character.
时间: 2024-08-18 07:34:21

L7.1 linux shell 条件判断与循环语句的相关文章

hell脚本编写 之 条件选择,条件判断,循环语句

1 概述 编写shell脚本,一般离不开条件选择,条件判断以及循环语句.掌握这三个语法,将大大提高脚本的编写效率,使得脚本编写更加灵活,完成X相对复杂的工作 2 条件选择if语句 if语句选择执行,逐条件进行判断,第一次遇为"真"条件时,执行其分支,而后结束整个if语句 if是根据判读条件的命令的退出状态来执行命令,if语句可嵌套 单分支 if 判断条件;then 条件为真的分支代码 fi 双分支 if 判断条件; then 条件为真的分支代码 else 条件为假的分支代码 fi 多分

Linux Shell脚本 几种循环语句创建用户的方法

大家好,我是孤云暮雨,今天给大家带来的是"Linux Shell脚本 几种循环语句创建用户的方法" 添加user1-user20用户 for循环: #!/bin/bash for i in {1..20} do useradd user$i echo "user$i Users to add success" done for循环(C风格): #!/bin/bash for ((i=1;i<=20;i++)) do useradd user$i &&a

Linux shell的条件判断、循环语句及实例

shell条件判断的两个特殊设备 /dev/null linux系统的空设备,也称为位桶,任何写入其中的数据均会被丢弃当你不想将标准化输出显示或者保存至文件时可以将文件从定向到/dev/null 禁止标准化输出 cat $filename > /dev/null 禁止标准化错误 rm $filename > /dev/null /dev/zero Linux的输入设备,可以用他初始化文件,可以无限制输出0, 另一个作用是用0去填充一个指定大小的文件 在条件判断语句中&&表示an

LINUX SHELL条件判断

算术运算的条件判断 [] [[]]: -eq -ne -lt -le -gt -ge (( )):><>=<== [[email protected] ~]# if (( 2 == 3));then echo '123'; fi [[email protected] ~]# if (( 2 >= 3));then echo '123'; fi [[email protected] ~]# if (( 2 <= 3));then echo '123'; fi 123[[e

java-条件判断和循环语句

条件判断和循环语句 if语句 if语句格式1: if(关系表达式) { 语句体 } 执行流程: 首先判断关系表达式看其结果是true还是false 如果是true就执行语句体 如果是false就不执行语句体 if语句格式2: if(关系表达式) { 语句体1; }else { 语句体2; } 执行流程 首先判断关系表达式看其结果是true还是false 如果是true就执行语句体1 如果是false就执行语句体2 if语句格式3: if(关系表达式1) { 语句体1; }else  if (关系

Shell脚本的条件控制和循环语句

条件判断:if语句 语法格式: if [ expression ] then Statement(s) to be executed if expression is true fi 注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误. if 语句通过关系运算符判断表达式的真假来决定执行哪个分支.Shell 有三种 if ... else 语句: if ... fi 语句 if ... else ... fi 语句 if ... elif ... else ... f

Sass学习笔记 -- 初步了解函数、运算、条件判断及循环

函数 sass定义了很多函数可供使用,当然你也可以自己定义函数,以@fuction开始.sass的官方函数链接为:sass fuction,实际项目中我们使用最多的应该是颜色函数,而颜色函数中又以lighten减淡和darken加深为最,其调用方法为lighten($color,$amount)和darken($color,$amount),它们的第一个参数都是颜色值,第二个参数都是百分比. //scss $baseFontSize:      10px !default; $gray:    

Python_条件判断和循环

条件判断和循环 author:lxy 条件判断让计算机自己选择做什么 循环让计算机做重复的工作 条件判断: if ...elif....else.... if <判断条件>: <语句块> elif <判断条件>: <语句块> else: <语句块> 说明: 用法感觉和Java没什么不同吧,除了语法写起来有限不一样 注意每一个判断条件之后和else加: elif 是else if是简写 判断条件可以简写,比如if x:只要x是非零数值.飞空字符串.

Shell 条件判断

传统if 从句子——以条件表达式作为 if条件 if [ 条件表达式 ] then command command command else command command fi       条件表达式 文件表达式 if [ -f  file ]    如果文件存在 if [ -d ...   ]    如果目录存在 if [ -s file  ]    如果文件存在且非空 if [ -r file  ]    如果文件存在且可读 if [ -w file  ]    如果文件存在且可写 if