Shell脚本语法-- if/then/elif/else/fi
来源:互联网 发布:mac装linux虚拟机 编辑:程序博客网 时间:2024/04/29 20:03
和C语言类似,在Shell中用if
、then
、elif
、else
、fi
这几条命令实现分支控制。这种流程控制语句本质上也是由若干条Shell命令组成的,例如先前讲过的
if [ -f ~/.bashrc ]; then . ~/.bashrcfi
其实是三条命令,if [ -f ~/.bashrc ]
是第一条,then . ~/.bashrc
是第二条,fi
是第三条。如果两条命令写在同一行则需要用;号隔开,一行只写一条命令就不需要写;号了,另外,then
后面有换行,但这条命令没写完,Shell会自动续行,把下一行接在then
后面当作一条命令处理。和[
命令一样,要注意命令和各参数之间必须用空格隔开。if
命令的参数组成一条子命令,如果该子命令的Exit Status为0(表示真),则执行then
后面的子命令,如果Exit Status非0(表示假),则执行elif
、else
或者fi
后面的子命令。if
后面的子命令通常是测试命令,但也可以是其它命令。Shell脚本没有{}括号,所以用fi
表示if
语句块的结束。见下例:
#! /bin/shif [ -f /bin/bash ]then echo "/bin/bash is a file"else echo "/bin/bash is NOT a file"fiif :; then echo "always true"; fi
:
是一个特殊的命令,称为空命令,该命令不做任何事,但Exit Status总是真。此外,也可以执行/bin/true
或/bin/false
得到真或假的Exit Status。再看一个例子:
#! /bin/shecho "Is it morning? Please answer yes or no."read YES_OR_NOif [ "$YES_OR_NO" = "yes" ]; then echo "Good morning!"elif [ "$YES_OR_NO" = "no" ]; then echo "Good afternoon!"else echo "Sorry, $YES_OR_NO not recognized. Enter yes or no." exit 1fiexit 0
上例中的read
命令的作用是等待用户输入一行字符串,将该字符串存到一个Shell变量中。
此外,Shell还提供了&&和||语法,和C语言类似,具有Short-circuit特性,很多Shell脚本喜欢写成这样:
test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)
&&相当于“if...then...”,而||相当于“if not...then...”。&&和||用于连接两个命令,而上面讲的-a
和-o
仅用于在测试表达式中连接两个测试条件,要注意它们的区别,例如,
test "$VAR" -gt 1 -a "$VAR" -lt 3
和以下写法是等价的
test "$VAR" -gt 1 && test "$VAR" -lt 3
- Shell脚本语法-- if/then/elif/else/fi
- Shell脚本语法-- if/then/elif/else/fi
- Shell脚本语法-- if/then/elif/else/fi
- Shell脚本语法--if/then/elif/else/fi
- shell 脚本 if then else fi
- shell语法if else elif
- 4 Bash If Statement Examples ( If then fi, If then else fi, If elif else fi, Nested if )
- 4 Bash If Statement Examples ( If then fi, If then else fi, If elif else fi, Nested if )
- Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif
- shell结构化命令if-then-elif-fi
- shell-007: if elif else
- Linux学习 分支(if-then fi, if then elif then fi, case in );;easc
- 第五章 shell 机构化脚本【if-else-fi】
- linux shell ---if...else...fi
- shell Learning [if elif else 的用法]
- Shell if elif else Code Example
- shell中的if elif else用法
- shell中if-elif-else用法
- MD(d)、MT(d)编译选项的区别
- 借生产者/消费者问题讲PV操作
- Android中的线程处理
- 稀疏表示+子空间学习 (ICCV2011)
- ostringstream用法
- Shell脚本语法-- if/then/elif/else/fi
- 转发ECCV2012感兴趣的文章列表
- 【怀念张国荣继续宠爱十年音乐会】下载
- jsp的九大内置对象?对应servlet中的java对象?
- Hibernate常用配置属性
- 恒和大风 - 机试题
- Windows下权限上下文
- log4j配置详解
- WideCharToMultiByte和MultiByteToWideChar函数的用法