Shell 必知必会 |
您所在的位置:网站首页 › 条件判断例子 › Shell 必知必会 |
目录 一、基本语法 1.1 if 1.2 if else 1.3 if elif 二、实例 2.1 if 语句 2.2 if else 语句 2.3 if elif 语句 三、总结 在 Shell 编程中,在判断的时候经常使用 if 语句,但是,Shell 中的 if 语句与 C/C++/Java 等语言中的形式还有有些差别的,下面结合实例进行说明。 一、基本语法if 语句主要有一下几种形式。 1.1 if(1)形式一 if condition; then 符合 condition 的执行语句 fi注意:结尾是将 if 倒过来写 fi 作为结束标志。 (2)形式二 可以将 then 写到与 if 在一行,也可以分行写,如下所示: if condition then 符合 condition 的执行语句 fi 1.2 if else单独的一个 if else 语句,如下所示: if condition then 符合 condition 的执行语句 else 不符合 condition 的执行语句 fi这里 then 也可以写到与 if 在一行中。 1.3 if elif注意:Shell 里将 else if 简写为 elif,elif 也要有 then,如下所示: if condition_1 then 符合 condition_1 的执行语句 elif condition_2 then 符合 condition_2 的执行语句 else 不符合 condition_1 和 condition_2 的执行语句 fi当然,还有更多的组合形式,这里就不一一说明了。 二、实例 2.1 if 语句 #!/bin/bash file="/root" #形式一 if [ -d $file ]; then echo "$file is directory!" fi #形式二 if [ -d $file ] then echo "$file is directory!" fi 2.2 if else 语句 #!/bin/bash file="/root" if [ -d $file ] then echo "$file is directory!" else echo "$file is not directory!" fi 2.3 if elif 语句 #!/bin/bash file="/root" if [ -f $file ] then echo "$file is regular file!" elif [ -d $file ] then echo "$file is directory!" else echo "$file is not regular file and directory" fi 三、总结if 语句判断逻辑各种编程语言都是通用的,在 Shell 中要注意if语句结尾使用 fi(if 倒过来写),else if 应写成 elif ,还有在写 if 和 elif 时别忘记 then。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |