linux嵌套if
⑴ linux bash的 while循环中不能使用if语句吗
while 语句中嵌套if语句:
while [ $1 ]
do
if [ -f $1 ] 《----- if 与
[ 之间一定要有空格
then
{......}
else
....
fi
shift
⑵ linux 系统- if case的使用和判断条件
在Linux系统中,if语句和case语句的使用及其判断条件如下:
if语句的使用及其判断条件: 基本格式: 基本的ifthenfi:用于简单的条件判断。 带有else的ifthenelsefi:当条件不满足时执行else部分的代码。 嵌套的ifelifelsefi结构:用于多个条件的判断,当满足某个条件时执行相应的代码块。
判断条件:
- 字符判断:检查字符串长度、是否为空、是否相等或不等,以及字符串间的大小关系。
- 文件判断:检查目录或文件是否存在、是否具有可读性、可执行性等属性。
- 整数比较:使用eq、ne、gt、ge、lt、le等符号进行比较。注意使用括号而非尖括号<>。
逻辑运算符:
- 在[]中避免直接使用and和or,可通过a和o进行替换,或在双括号[[ ]]中使用。
case语句的使用及其判断条件: 基本格式:case语句用于根据变量的不同值执行不同的命令。每个case分支对应一个特定的值或字符范围,default部分用于处理未匹配到的情况。
- 判断条件:
- 在case结构中,每个case分支后面跟随的是要匹配的值或字符范围,以及相应的命令。
- default部分用于处理所有未匹配到的情况,通常放在最后。
注意事项: 在使用if和case语句时,务必注意语法的严谨性,包括空格的使用、表达式的正确格式等。 确保条件判断部分逻辑正确,以避免程序执行出错。
⑶ 在Linux的系统Shell脚本中使用if语句的方法
Bourne Shell 的 if 语句和大部分编程语言一样 - 检测条件是否真实,如果条件为真,shell 会执行这个 if 语句指定的代码块,如果条件为假,shell 就会跳过 if 代码块,继续执行之后的代码。
if 语句的语法:
复制代码代码如下:if [ 判断条件 ]then
command1
command2
……..
last_command
fi
Example:
#!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi
if-else 语句:
除了标准的 if 语句之外,我们还可以加入 else 代码块来扩展 if 语句。这么做的主要目的是:如果 if 条件为真,执行 if 语句里的代码块,如果 if 条件为假,执行 else 语句里的代码块。
语法:
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example:
复制代码代码如下:#!/bin/bashnumber=150
if [ $number -gt 250 ]
then
echo "Number is greater"
else
echo "Number is smaller"
fi
If..elif..else..fi 语句 (简写的 else if)
Bourne Shell 的 if 语句语法中,else 语句里的代码块会在 if 条件为假时执行。我们还可以将 if 语句嵌套到一起,来实现多重条件的检测。我们可以使用 elif 语句(else if 的缩写)来构建多重条件的检测。
语法 :
then
command1
command2
……..
last_command
elif [ 判断条件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example :
复制代码代码如下:#!/bin/bashnumber=150
if [ $number -gt 300 ]
then
echo "Number is greater"
elif [ $number -lt 300 ]
then
echo "Number is Smaller"
else
echo "Number is equal to actual value"
fi
多重 if 语句 :
If 和 else 语句可以在一个 bash 脚本里相互嵌套。关键词 “fi” 表示里层 if 语句的结束,所有 if 语句必须使用 关键词 “fi” 来结束。
基本 if 语句的嵌套语法:
复制代码代码如下:if [ 判断条件1 ]then
command1
command2
……..
last_command
else
if [ 判断条件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi
Example:
复制代码代码如下:#!/bin/bashnumber=150
if [ $number -eq 150 ]
then
echo "Number is 150"
else
if [ $number -gt 150 ]
then
echo "Number is greater"
else
echo "'Number is smaller"
fi
fi