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

    • 一个等于号= 是赋值
相关文章
相关标签/搜索