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/bashn=`wc -l /tmp/lala`if [ -z "$n" ]then echo error exitelif [ $n -gt 100 ]then echo djsjddfi[root@hf-01 shell]# sh -x file1.sh++ wc -l /tmp/lalawc: /tmp/lala: 没有那个文件或目录+ n=+ '[' -z '' ']'+ echo errorerror+ exit[root@hf-01 shell]#
[root@hf-01 shell]# vim file1.sh[root@hf-01 shell]# cat !$cat file1.sh#! /bin/bashif [ ! -f /tmp/lala ]then echo "/tmp/lala not exit." exitfin=`wc -l /tmp/lala`if [ -z "$n" ]then echo error exitelif [ $n -gt 100 ]then echo djsjddfi[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; fiok[root@hf-01 shell]# echo $b[root@hf-01 shell]# if [ -n "$b" ]; then echo $b; else echo "b is null"; fib 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/passwdzabbix: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"; fizabbix exist[root@hf-01 shell]#
-
if [ ! -e file ]; then 表示文件不存在时会怎么样
-
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…
-
[ ] 中不能使用<,>,==,!=,>=,<=这样的符号
- 一个等于号= 是赋值