博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20.7 if特殊用法
阅读量:7206 次
发布时间:2019-06-29

本文共 1794 字,大约阅读时间需要 5 分钟。

hot3.png

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…

  • [ ] 中不能使用<,>,==,!=,>=,<=这样的符号

    • 一个等于号= 是赋值

转载于:https://my.oschina.net/u/3707314/blog/1618018

你可能感兴趣的文章
数据挖掘算法 1 ID3(python)
查看>>
FPGA机器学习之学习的方向
查看>>
WebBrowser控件使用相关
查看>>
【Android】1.1 开发环境安装和配置
查看>>
站点公司亚马逊砸了10亿也没能做成智能手机,技术是须要沉淀和积累的
查看>>
[数据库]SQL Server 用户NT AUTHORITY\IUSR 登录失败
查看>>
轻松学会多线程(四)——synchronized同步keyword知多少
查看>>
Apache Kylin 部署之不完全指南
查看>>
php中将SimpleXMLElement Object数组转化为普通数组
查看>>
docker学习(7) docker-compose使用示例
查看>>
Android 推断当前Activity是不是最后一个Activity 以及 应用或Activity是否存在
查看>>
【Android】6.3 ProgressDialog
查看>>
设计模式六大原则——迪米特法则(LoD)
查看>>
HtmlAgilityPack 之 HtmlNode类
查看>>
[转]Java Web基础——Action+Service +Dao三层的功能划分
查看>>
ngx.location.capture 只支持相对路径,不能用绝对路径
查看>>
自己在OC考试中的试题
查看>>
向 Git 服务器添加 SSH 公钥
查看>>
Lua学习笔记5:类及继承的实现
查看>>
Vagrant工具
查看>>