1.if判断
①简单判断,如果满足条件,返回OK
#!/bin/bash a=5 if[$a-gt3] then echo"OK" fi [root@localhosttest_shell]#./test.sh OK
②两个条件时,可以使用elif及else
#!/bin/bash a=5 if[$a-lt3] then echo"<3" elif[$a-lt6] then echo"<6" else echo"NotOK" fi [root@localhosttest_shell]#./test.sh <6 [root@localhosttest_shell]#bash-xtest.sh +a=5 +'['5-lt3']' +'['5-lt6']' +echo'<6' <6
逻辑判断表达式中的常用符号:
-lt:小于
-gt:大于
-eq:等于
-le:小于等于
-ge:大于等于
||:或者
&&:并且
!:非
①-f选项判断文件是否存在
#!/bin/bash a=/tmp/test_shell/f_exist.txt if[-f$a] then echo"$aexist" else touch$a echo"FileCreated" fi
执行结果如下:
[root@bogontest_shell]#sh-xtest.sh +a=/tmp/test_shell/f_exist.txt +'['-f/tmp/test_shell/f_exist.txt']' +touch/tmp/test_shell/f_exist.txt +echo'FileCreated' FileCreated [root@bogontest_shell]#sh-xtest.sh +a=/tmp/test_shell/f_exist.txt +'['-f/tmp/test_shell/f_exist.txt']' +echo'/tmp/test_shell/f_exist.txtexist' /tmp/test_shell/f_exist.txtexist
②-d选项判断目录是否存在,-e则表示检查文件或者目录是否存在
#!/bin/bash a=/tmp/test_shell/folder_test if[-d$a] then echo"Folder:$aexist" else mkdir$a echo"FolderCreated" fi
执行结果如下:
[root@bogontest_shell]#sh-xtest_folder.sh +a=/tmp/test_shell/folder_test +'['-d/tmp/test_shell/folder_test']' +mkdir/tmp/test_shell/folder_test +echo'FolderCreated' FolderCreated [root@bogontest_shell]#sh-xtest_folder.sh +a=/tmp/test_shell/folder_test +'['-d/tmp/test_shell/folder_test']' +echo'Folder:/tmp/test_shell/folder_testexist' Folder:/tmp/test_shell/folder_testexist
③判断文件是否可读(-r),可写(-w),可执行(-x)
#!/bin/bash a=/tmp/test_shell/readable.sh if[-r$a] then echo"$areadable" fi
执行结果如下:
[root@bogontest_shell]#sh-xreadable.sh +a=/tmp/test_shell/readable.sh +'['-r/tmp/test_shell/readable.sh']' +echo'/tmp/test_shell/readable.shreadable' /tmp/test_shell/readable.shreadable