test:可以用中括號替代宴偿,中括號前后要有空格?
[ " " ] && echo true:
里面有數(shù)值就不算空 沒有賦值也算空?
判斷文件的各種屬性:
-a? FILE? 判斷文件是否存在
-b? 塊文件
-c? 字符文件
-d? 文件夾
-f? ? 普通文件
-g? ? sgid文件
-w? ?可寫
-x? ? 可執(zhí)行
判斷某個文件存不存在,存在就不創(chuàng)建了
FILE=/data/test.txt ; [ -e "$FILE" ] || touch $FILE
[ -e "$FILE" ] 雙引號的存在有沒有什么影響:
如果[ -e $FILEE ]? 相當于 [ -e ],變成判斷字符串的數(shù)值限煞,所以是成立
[ $x -gt 10 ]? ?兩個變量比較
-bash: [: -gt: unary operator expected
無法確保$x是否為空:
[ "$x" -gt 10 ]:
加上雙引號螺戳,顯示輸入數(shù)字比較
如何確保判斷是數(shù)字:
[[? ? ?]]:里面支持正則表達式融涣,需要在里面添加? =~? 包含
[root@Centos7 ~]# str=good; [[ $str =~ oo ]] && echo true
true
[root@Centos7 ~]# str=gooood; [[ $str =~ o{2,} ]] && echo true
true
如何判斷數(shù)字:
n=a123b; [[ "$n" =~ ^[[:digit:]]+$ ]] && echo digit
判斷出數(shù)字的情況下參與運算
[[]]:用于正則表達式匹配的情況下稀颁,[]:文件的比較肢藐,數(shù)字比較。
判斷一個文件的文件名是否sh后綴:
FILE=f.sh;? [[ $FILE =~ \.sh$ ]]? && echo.sh
[root@Centos7 ~]# ifconfig |grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
判斷是不是合法ip:[root@Centos7 ~]# ip=122.2.3.4; [[ $ip =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] && echo legal ip || echo not legal ip
legal ip
判斷:
判斷一個文件是不是sh后綴巍虫,是不是可執(zhí)行文件彭则,如果是就執(zhí)行,不是的話就不執(zhí)行它
file=/data/test.sh; [[ $file =~ \.sh$ ]] && [ -x "$file" ] && $file
某個文件是否可讀并且也可寫:
[? ?-r? "$file"? -a? -w? "$file"? ]? && echo $file is readable and writable
/data/test.sh is readable and writable
即使root在內(nèi)如果沒有執(zhí)行權限的話占遥,也是執(zhí)行不起來的
13 [ $# -eq 0 ] && { echo "Usage: `basename $0` USERNAME" ; exit 10; }
14 id $1 &> /dev/null && { echo "User $1 is exist"; exit 20; }
15 useradd $1 &> /dev/null && { echo $1 is created :echo magedu |passwd --stdin $1 &> /dev/null ; } || { ech? ? o "Error!" exit 30; }? ? ? ? ? ? ? ? ? ? ? ? ??
? ?創(chuàng)建賬號
chmod 給文件加執(zhí)行權限俯抖,如果說chmod的執(zhí)行權限被取消呢
setfacl -m u:root:rwx /usr/bin/chmod
重新給chmod增加權限