20.7 if特殊用法

if 特殊用法

  • if [ -z "$a" ] 這個表示當變量a的值爲空時會怎麼樣
  • if [ -n "$a" ] 表示當變量a的值不爲空
  • if grep -q '123' 1.txt; then 表示若是1.txt中含有'123'的行時會怎麼樣
  • if [ ! -e file ]; then 表示文件不存在時會怎麼樣
  • if (($a<1)); then …等同於 if [ $a -lt 1 ]; then…
  • [ ] 中不能使用<,>,==,!=,>=,<=這樣的符號

if 特殊用法

  • if -z或者if -n 都不能做用在文件上,只能做用在變量上。
  • if [ -z "$a" ] 這個表示當變量a的值爲空時會怎麼樣
    • -z 表示爲空
  • !-z=-n
  • !-n=-z
[root@hf-01 shell]# vim file1.sh
[root@hf-01 shell]# cat !$
cat file1.sh
#! /bin/bash
n=`wc -l /tmp/lala`
if [ -z "$n" ]
then
	echo error
	exit
elif [ $n -gt 100 ]
then
	echo djsjdd
fi
[root@hf-01 shell]# sh -x file1.sh
++ wc -l /tmp/lala
wc: /tmp/lala: 沒有那個文件或目錄
+ n=
+ '[' -z '' ']'
+ echo error
error
+ exit
[root@hf-01 shell]#
[root@hf-01 shell]# vim file1.sh
[root@hf-01 shell]# cat !$
cat file1.sh
#! /bin/bash
if [ ! -f /tmp/lala ]
then
	echo "/tmp/lala not exit."
	exit
fi
n=`wc -l /tmp/lala`
if [ -z "$n" ]
then
	echo error
	exit
elif [ $n -gt 100 ]
then
	echo djsjdd
fi
[root@hf-01 shell]# sh file1.sh
/tmp/lala not exit.
[root@hf-01 shell]#
  • if [ -n "$a" ] 表示當變量a的值不爲空,或者說這個文件內容不爲空
    • -n 判斷變量的時候,須要用""雙引號引發來,如果文件的時候,則不須要用雙引號引發來
[root@hf-01 shell]# if [ -n 01.sh ]; then echo ok; fi
ok
[root@hf-01 shell]# echo $b

[root@hf-01 shell]# if [ -n "$b" ]; then echo $b; else echo "b is null"; fi
b is null
[root@hf-01 shell]#
  • if grep -q '123' 1.txt; then 表示若是1.txt中含有'123'的行時會怎麼樣
    • grep -wq 其中-w 後跟一個單詞,-q僅僅作一個過濾
    • 好比,如果想建立一個用戶,直接取反便可,如if ! grep -wq 'zabbix' /etc/passwd; then useradd zabbix; fi zabbix exist
[root@hf-01 shell]# grep -w 'zabbix' /etc/passwd
zabbix:x:998:995:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin
[root@hf-01 shell]# if grep -wq 'zabbix' /etc/passwd; then echo "zabbix exist"; fi
zabbix exist
[root@hf-01 shell]#
  • if [ ! -e file ]; then 表示文件不存在時會怎麼樣shell

  • if (($a<1)); then …等同於 if [ $a -lt 1 ]; then…vim

  • [ ] 中不能使用<,>,==,!=,>=,<=這樣的符號bash

    • 一個等於號= 是賦值
相關文章
相關標籤/搜索